HDU 5441 Travel (带权并查集 离线)
题目
题意
n个点,m条边,每条边权值val
q次询问,每次有一个值v,将图中所有小于v的边标记出来组成新图,求里面有多少个点对可以相互到达(a -> b 和 b -> a 算两个)
解法
离线并查集,记录每个集合里面点的个数,每次合并两个点数为x, y的集合,对ans的贡献为 \((x+y)\*(x+y-1) - x\*(x-1) - y\*(y-1)\) 整理得\(2xy\)
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e4 + 100;
const int M = 1e5 + 100;
const int K = 5e3 + 100;
struct Edge {
int u, v, val;
friend bool operator < (const Edge& a, const Edge& b) {
return a.val < b.val;
}
} edge[M];
struct Question {
int val, pos;
friend bool operator < (const Question& a, const Question& b) {
return a.val < b.val;
}
} q[K];
int fa[N], ans[K], num[N];
int find(int u) {
if(fa[u] == u) {
return u;
}
else {
return fa[u] = find(fa[u]);
}
}
int main() {
int T;
int n, m, k;
scanf("%d", &T);
while(T--) {
scanf("%d %d %d", &n, &m, &k);
for(int i = 0; i < m; i++) {
scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].val);
}
for(int i = 0; i < k; i++) {
scanf("%d", &q[i].val);
q[i].pos = i;
}
sort(edge, edge + m);
sort(q, q + k);
for(int i = 0; i <= n; i++) {
fa[i] = i;
num[i] = 1;
}
int j = 0, sum = 0;
for(int i = 0; i < k; i++) {
while(j < m && edge[j].val <= q[i].val) {
int fu = find(edge[j].u);
int fv = find(edge[j].v);
if(fu != fv) {
int x = num[fu];
int y = num[fv];
fa[fv] = fu;
// sum -= x * (x - 1);
// sum -= y * (y - 1);
// sum += (x + y) * (x + y - 1);
sum += 2 * x * y;
num[fu] += y;
num[fv] = 0;
}
j++;
}
ans[q[i].pos] = sum;
}
for(int i = 0; i < k; i++) {
printf("%d\n", ans[i]);
}
}
return 0;
}
来源
2015 ACM/ICPC Asia Regional Changchun Online