Problem Description
Problem Analysis
This problem appeared in the last individual contest
but I wrote it with a search-based mindset at the time
Roughly, when an infected person is encountered
find every group that contains this person
and recurse on each of its members
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
| #include<stdio.h>
#include<string.h>
int n,z,cnt;
int a[500][1000];
int b[30000];
void s(int m) {
if(!b[m]) {
cnt++;
b[m]=1;
} else
return ;
for(int i=0; i<z; i++) {
for(int j=1; j<=a[i][0]; j++) {
if(a[i][j]==m) {
for(int k=1; k<=a[i][0]; k++) {
if(a[i][k]!=m)
s(a[i][k]);
}
break;
}
}
}
}
int main() {
while(scanf("%d %d",&n,&z),n!=0||z!=0) {
memset(b,0,sizeof(b));
memset(a,0,sizeof(a));
for(int i=0; i<z; i++) {
scanf("%d",&a[i][0]);
for(int j=1; j<=a[i][0]; j++) {
scanf("%d",&a[i][j]);
}
}
cnt=0;
s(0);
printf("%d\n",cnt);
}
return 0;
}
|
But this problem is still more convenient with the Union-Find idea
That is, merge sets directly according to group relations
and finally count how many are in the same set as person 0
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
51
| #include<stdio.h>
int par[30200];
int rank[30200];
int find(int m) {
if(m==par[m])
return m;
else
return par[m]=find(par[m]);
}
void unite(int x,int y) {
x=find(x);
y=find(y);
if(x==y)
return;
if(rank[x]<rank[y])
par[x]=y;
else {
par[y]=x;
if(rank[x]==rank[y])
rank[x]++;
}
}
int main() {
int n,m;
while(scanf("%d %d",&n,&m),n||m) {
for(int i=0; i<n; i++) {
par[i]=i;
rank[i]=0;
}
for(int i=0; i<m; i++) {
int k;
scanf("%d",&k);
int t;
scanf("%d",&t);
k--;
while(k--) {
int p;
scanf("%d",&p);
unite(t,p);
t=p;
}
}
int cnt=0;
for(int i=0; i<n; i++) {
if(find(i)==find(0))
cnt++;
}
printf("%d\n",cnt);
}
return 0;
}
|
Problem address:【POJ】[1611]The Suspects