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

你可能感兴趣的文章
Prometheus监控k8s集群使用邮箱和微信告警!
查看>>
Prometheus监控mysq数据库实战
查看>>
prometheus监控nginx实战
查看>>
Prometheus监控redis数据库实战
查看>>
Prometheus监控教程:使用Grafana展示主机基本信息
查看>>
pytorch中如何使用预训练词向量
查看>>
Prometheus监控教程:使用PromQL查询监控数据(上篇)
查看>>
Prometheus监控教程:使用PromQL查询监控数据(下篇)
查看>>
Pytorch中关于forward函数的理解与用法
查看>>
Prometheus监控教程:安装部署
查看>>
Prometheus监控教程:配置介绍
查看>>
Pytorch中tqdm进度条的使用
查看>>
Prometheus(2):SpringBoot 2.X集成Prometheus
查看>>
Promise 原理解析与实现(遵循Promise/A+规范)
查看>>
PyTorch:传递 numpy 数组进行权重初始化
查看>>
PyTorch-Tutorials【pytorch官方教程中英文详解】- 8 Save and Load Model
查看>>
promise.all是并发执行吗_攻破面试灵魂拷问,解读Java并发编程的艺术,本文带你深入l理解...
查看>>
PyTorch-Tutorials【pytorch官方教程中英文详解】- 7 Optimization
查看>>
promise总结
查看>>
Propel项目改为基于TensorFlow.js
查看>>