题意:先输入n,然后输入n行,同一行的两个数表示的互为朋友,要求找到最多的直接朋友或间接朋友。比如
41 23 45 61 6 其中1、2、5、6是朋友,3、4是朋友,所以输出4 测试样例:
41 23 45 61 641 23 45 67 8
输出 4 2 注意:init()写在while循环里面,注意n=0的特殊情况,注意数据范围!
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 int n,p,q; 7 int f[10000010],num[10000010]; 8 void init() 9 {10 for(int i=1;i<10000010;i++)11 {12 f[i]=i;13 num[i]=1;14 }15 }16 int find(int x)17 {18 if(f[x]!=x)19 return f[x]=find(f[x]);20 }21 void merge(int x,int y)22 {23 int tx=find(x);24 int ty=find(y);25 if(tx!=ty)26 {27 f[tx]=ty;28 num[ty]+=num[tx];29 }30 return ;31 }32 int main()33 {34 while(~scanf("%d",&n))35 {36 init();37 if(n==0)38 {39 printf("1\n");40 continue; 41 }42 int maxn=0;43 while(n--)44 {45 cin>>p>>q;46 if(p>maxn)47 {48 maxn=p;49 } 50 if(q>maxn)51 {52 maxn=q;53 }54 merge(p,q); 55 }56 int Max=0; 57 for(int i=1;i<=maxn;i++)58 {59 // cout< < Max)61 {62 Max=num[i];63 } 64 }65 cout< <