Problem Description
Problem Analysis
Union-Find doesn’t feel like a great fit for this problem
The code seems very easy to get bugs in
Though the test data doesn’t seem very strict (there’s still quite a lot of it)
Plain brute-force DFS will also TLE
And if you do use DFS you need to build the tree first
With a weighted Union-Find, the main thing to watch out for is
that you must not set the parent of 0 to some other node
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| #include<stdio.h>
int par[100200],ran[100200];
int find(int m) {
if(m==par[m])
return m;
else {
ran[m]+=ran[par[m]];
return par[m]=find(par[m]);
}
}
void unite(int x,int y) {
if(x>y) {
int t=x;
x=y;
y=t;
}
int a=find(x);
int b=find(y);
if(x==y)
return ;
else {
par[b]=a;
ran[b]=ran[x]-ran[y]+1;
}
}
int main() {
int T;
scanf("%d",&T);
while(T--) {
int n,d;
scanf("%d %d",&n,&d);
for(int i=0; i<n; i++) {
ran[i]=0;
par[i]=i;
}
for(int i=1; i<n; i++) {
int a,b;
scanf("%d %d",&a,&b);
unite(a,b);
}
int res=0;
for(int i=0; i<n; i++) {
if(find(i)==0&&ran[i]>d)
res++;
}
printf("%d\n",res);
}
return 0;
}
|
Reference blog: hdu 4707 Pet【Weighted Union-Find】 – mengxiang000000