题解:P11615 【模板】哈希表

· · 题解

Update:修改措辞。

注意到 unordered_map、gp_hash_table 或 cc_hash_table 都被卡了。参考这篇 Codeforces 博客:https://codeforces.com/blog/entry/62393。我们给 hash 值添加当前时间,被卡的概率就会大大降低。然后就可以直接使用 unordered_map、gp_hash_table 或 cc_hash_table 了!

示例代码:

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define int uint64_t
#define rep(i,a,b) for(int i(a);i<=(b);++i)
using namespace std;
char buf[1<<23],*p1=buf,*p2=buf,ubuf[1<<23],*u=ubuf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
template<typename TP> inline TP read(TP &num)
{
    TP x=0;
    int f=0;
    char ch=getchar();
    while(ch<48||ch>57) f|=ch=='-',ch=getchar();
    while(48<=ch&&ch<=57) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
    return num=f?-x:x;
}
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
int n,x,y,ans;
__gnu_pbds::gp_hash_table<int,int,custom_hash> hashmap;
signed main()
{
    read(n);
    rep(i,1,n)
    {
        read(x),read(y);
        ans+=i*hashmap[x];
        hashmap[x]=y;
    }
    cout<<ans<<endl;
    return 0;
}