题解:P11615
gavinliu266 · · 题解
思路
我们知道,哈希可能被卡,当哈希冲突较多时可能超时。
于是我们考虑哈希冲突时使用拉链法,但是使用 map 代替链表,这样保证最坏单次
但是常数很大,需要合理调参。
代码实现
可以跑进 2 秒,记录。
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
mt19937 gen(time(NULL));
const ll N = 6.7e6 + 5;
const ll M = 6.7e6 - gen() % 50 - 1;
// 防卡。当然,可以出 50 组数据来都卡一遍,但是这样其它最坏单次 O(n) 的也都可以卡没
char buf[1 << 17], *p1 = buf, *p2 = buf;
#define gc() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<16, stdin), p1==p2) ? EOF : *p1++)
inline ll rd() {
ll x = 0;
char ch = gc();
while(ch < '0' || ch > '9') ch = gc();
while(ch >= '0' && ch <= '9') x = x * 10 + (ch ^ 48), ch=gc();
return x;
}
int n;
ll x, y;
map<ll, ll> hsh[N];
int main() {
scanf("%d", &n);
ll ans = 0;
for(ll i = 1; i <= n; ++i) {
x = rd(), y = rd();
int h = x % M;
ans += i * hsh[h][x];
hsh[h][x] = y;
}
printf("%llu\n", ans);
}