加油。
To be better.
Topic links:
https://vjudge.net/problem/POJ-1611
Topic effect:
to give you a n and m, n represents the total number of students, m represents the number of groups, the next m lines, each input a number of student representative bodies in t, t enter the next number represents students in this group. Note that once the community might have a SARS virus infection, then the whole group on SARS virus are likely infected. 0 is the default number of possible SARS virus infection.
Solution:
This is actually a disjoint-set template title, but first start I stuck in how to make all of those infected index points to 0, in fact, not be used as such, requires only conventional combined collections, and finally from 1 to traverse n 0 and about who is an ancestor that Find (x) == Find (0 );
AC Code:
#include<iostream>
using namespace std;
struct node
{//我这里用的是结构题,方便路径压缩
int x,pre,rak;
} f[30011];
int n,m;
void Init()
{//初始化
for(int i=0; i<=n; i++)
{
f[i].pre=i;
f[i].rak=1;
}
}
int Find(int x)
{//查找函数
if(f[x].pre==x)
return x;
else
return Find(f[x].pre);
}
void Union(int x,int y)
{//合并(路径压缩优化)
int rx=Find(f[x].pre);
int ry=Find(f[y].pre);
if(rx!=ry)
{
if(f[rx].rak<f[ry].rak)
f[rx].pre=f[ry].pre;
else
{
f[ry].pre=f[rx].pre;
if(f[rx].rak==f[ry].rak)
f[rx].rak++;
}
}
}
int Query()
{//查询一共有多少个可能的感染者
int t=Find(f[0].pre);
int ans=1;
for(int i=1;i<=n;i++)
{
if(t==Find(f[i].pre))
ans++;
}
return ans;
}
int main()
{
int t,a,b;
while(cin>>n>>m)
{
if(n==0)
break;
if(m==0)
cout<<1<<endl;
else
{
Init();
for(int i=1; i<=m; i++)
{
cin>>t;
for(int j=1; j<=t; j++)
{
if(j==1)
cin>>a;//第一个数单独输入,方便后续合并
else
{
cin>>b;
Union(a,b);
}
}
}
cout<<Query()<<endl;
}
}
return 0;
}