博客
关于我
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双版本下创建一个Scrapy(西瓜皮)项目
查看>>
Python双版本下No module named 'requests'
查看>>
python及pycharm2018软件安装教程
查看>>
python去重txt文本_Python实现的txt文件去重功能示例
查看>>
python去掉列表的逗号,从Python列表项中删除标点符号
查看>>
Python卸载所有包
查看>>
python单线程下实现多个socket并发
查看>>
Python单元测试框架介绍(超详细~)
查看>>
Python单元测试框架
查看>>
python单元测试之unittest
查看>>
Python单元测试unittest实战
查看>>
Python单元测试-模拟VS补丁
查看>>
python协程实时输出_Python 协程以及事件循环的问题,怎么知道 IO 读取结束了呢?...
查看>>
Python十进制&;包提供错误的结果
查看>>
Python化身“安全老中医”:一键搞定工控系统漏洞,从零基础到精通,收藏这篇就够了!
查看>>
Python加速运行技巧
查看>>
python办公自动化基础遍历文件夹
查看>>
python办公自动化基础输出文件和文件夹
查看>>
python办公自动化基础搜索文件
查看>>
python知识:@classmethod和@staticmethod的异同
查看>>