博客
关于我
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/

你可能感兴趣的文章
Position属性四个值:static、fixed、absolute和relative的区别和用法
查看>>
POSIX thread编程中关于临界区内条件变量的分析
查看>>
POSIX与程序可移植性
查看>>
posix多线程有感--自旋锁
查看>>
SpringBoot中集成海康威视SDK实现布防报警数据上传/交通违章图片上传并在linux上部署(附示例代码资源)
查看>>
POSIX标准和XSI扩展
查看>>
post install error,please remove node_moules before retry
查看>>
postcss-pxtorem 参数之selectorBlackList、exclude的用法
查看>>
Postek博思得标签打印机更换电脑,打印出来标签空白
查看>>
postfix+ dovecot搭建邮件服务器
查看>>
postfix在邮件服务器中的使用
查看>>
PostGIS 3.1.2软件安装详细教程(地图工具篇.8)
查看>>
PostGIS中获取所有EPSG的编码以及对应Proj4字符串
查看>>
SpringBoot中集成海康威视SDK实现布防报警数据上传/交通违章图片上传并在linux上部署(附示例代码资源)
查看>>
PostGIS在Windows上的下载与安装
查看>>
Qt开发——网络编程之UDP客户端
查看>>
postgis数据库优化_postgresql 性能优化
查看>>
postgis求面积、交集等相关函数
查看>>
postgis相关函数
查看>>
Postgres Docker版本安装mysql_fdw 插件
查看>>