P8026 [ONTAK2015] Bajtocja 题解
题目传送门
首先判断是否在同一个连通块里面很容易想到路径压缩并查集。
然后要在每个图里面都连通可以 bitset 或者哈希。
但是这题哈希更好,大概就是对每个点在不同图上的
然后考虑修改,发现这有可能会对多个点的
然后 unordered_map 就行了。
还是放弃了我的 hval,呜呜呜。
#include<bits/stdc++.h>
using namespace std;
const int D = 205, N = 5e3 + 5;
#define ll long long
#define ull unsigned ll
int inline read() {
int num = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
num = (num << 3) + (num << 1) + (ch ^ 48);
ch = getchar();
}
return num * f;
}
random_device seed;
mt19937_64 gen(seed());
int d, n, m, ans, fa[D][N];
vector<int> t[D][N];
ull hsh[N], w[D];
unordered_map<ull, int> cnt;
void add(ull x) { ans += cnt[x] << 1 | 1; ++cnt[x]; }
void del(ull x) { --cnt[x], ans -= cnt[x] << 1 | 1; }
int main() {
#ifdef file
freopen("P8026.in", "r", stdin);
freopen("P8026.out", "w", stdout);
#endif
d = read(), n = read(), m = read();
for(int i = 1; i <= d; ++i) w[i] = gen();
for(int i = 1; i <= d; ++i) {
for(int u = 1; u <= n; ++u) {
fa[i][u] = u;
hsh[u] += u * w[i];
t[i][u].emplace_back(u);
}
}
for(int u = 1; u <= n; ++u) add(hsh[u]);
while(m--) {
int u = read(), v = read(), k = read();
u = fa[k][u], v = fa[k][v];
if(u == v) { printf("%d\n", ans); continue; }
if(t[k][v].size() > t[k][u].size()) swap(u, v);
for(int x : t[k][v]) {
t[k][u].emplace_back(x);
fa[k][x] = u, del(hsh[x]);
hsh[x] += (u - v) * w[k], add(hsh[x]);
}
printf("%d\n", ans);
}
return 0;
}