hdoj1829 基础并查集
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1829
感慨下。。基础并查集都搞很久。、
h数组表示第一个与它发生关系的人,很明显当h[i]不等于0的时候h[i]肯定要与当前跟i发生关系的合并,当查找集合时发生关系的人在一个集合就是同性恋了
yy:这关系真邪恶!!
献上ac代码
1 #include<stdio.h> 2 #include<string.h> 3 #define maxn 2005 4 int h[maxn], ra[maxn]; 5 void init() 6 { 7 int i; 8 memset(h,0,sizeof(h)); 9 for(i=1;i<=2000;i++) 10 ra[i]=i; 11 12 } 13 14 int find(int x) 15 { 16 if(ra[x]==x) 17 return ra[x]; 18 return ra[x]=find(ra[x]); 19 20 } 21 void marge(int a,int b) 22 { 23 int s=find(a); 24 int ss=find(b); 25 if(s!=ss) 26 { 27 ra[s]=ss; 28 } 29 } 30 int main() 31 { 32 int t; 33 scanf("%d",&t); 34 int count=1; 35 while(t--) 36 { 37 int i, flag=0; 38 int n,m; 39 init(); 40 scanf("%d %d",&n,&m); 41 for(i=1;i<=m;i++) 42 { 43 int x, y; 44 scanf("%d %d",&x,&y); 45 if(flag) 46 continue; 47 if(find(x)==find(y)) 48 { 49 flag=1; 50 continue; 51 } 52 if(h[x]) 53 marge(h[x],y); 54 else 55 h[x]=y; 56 if(h[y]) 57 marge(h[y],x); 58 else 59 h[y]=x; 60 61 62 } 63 printf("Scenario #%d:\n",count++); 64 if(flag) 65 printf("Suspicious bugs found!\n\n"); 66 else 67 printf("No suspicious bugs found!\n\n"); 68 69 } 70 return 0; 71 }