跳到正文

题解

题解:P11615

gavinliu266约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P11615

版本

  1. v1当前

思路

我们知道,哈希可能被卡,当哈希冲突较多时可能超时。

于是我们考虑哈希冲突时使用拉链法,但是使用 map 代替链表,这样保证最坏单次 O(log⁡n)O(\log n),期望单次 O(1)O(1)。

但是常数很大,需要合理调参。

代码实现

可以跑进 2 秒,记录。

C++
#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);
}
原文