博客
关于我
Lougu P1102 A-B 数对【hash】
阅读量:354 次
发布时间:2019-03-04

本文共 795 字,大约阅读时间需要 2 分钟。

这道题的暴力破解其实非常简单,但我们选择使用哈希表来实现,这样可以更高效地解决问题。

首先,我们需要包含必要的头文件:

#include 
#include
#include
#include
using namespace std;

接下来,我们定义了一些常量和变量:

#define P 4000037long long a[P], b[200010], c[P];long long n, C, x, qm, ans;

然后,我们定义了两个关键函数:

long long hash(long long x) {    return x % P;}long long dw(long long x) {    long long j = 0;    qm = hash(abs(x));    while (a[hash(j + qm)] != x && c[hash(j + qm)] != 0) {        j++;    }    return hash(j + qm);}

最后是主函数的逻辑:

int main() {    scanf("%lld%lld", &n, &C);    for (int i = 1; i <= n; i++) {        scanf("%lld", &b[i]);        a[dw(b[i])] = b[i];        c[dw(b[i])]++;    }    for (int i = 1; i <= n; i++) {        ans += c[dw(b[i] - C) % P];    }    cout << ans << endl;}

通过这种方式,我们可以高效地完成题目的要求。

转载地址:http://gsle.baihongyu.com/

你可能感兴趣的文章
Python 无法安装包
查看>>
python 日历小部件 - 返回用户选择的日期
查看>>
Python 日志管理封装
查看>>
python 时间函数小总结
查看>>
Python 是否优化尾递归?
查看>>
Python 更新set
查看>>
Python 最强 IDE 详细使用指南!
查看>>
Python 有一个不可变的列表吗?
查看>>
Python 机器学习入门之 pandas 的使用
查看>>
Python 机器学习实战
查看>>
python 杀死子进程_subprocess.popen.kill杀死所有子进程
查看>>
Python 条件语句与循环结构详解
查看>>
Python 条件运算符解决方法如何工作?
查看>>
python 枚举类型
查看>>
Python 查询 Mongodb数据库
查看>>
python 查询Neo4j多节点的多层关系
查看>>
python多处理参数:深拷贝?
查看>>
Python多处理使用队列写入同一个文件
查看>>
Python多处理.Process:从局部变量开始
查看>>
Python多处理-进程数
查看>>