大招秒杀

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct ufset *UFset;
 4 struct ufset
 5 {
 6     int parent[100001];
 7     int root[100001];
 8 }UFS;
 9 int UFfind(int e,UFset U)
10 {
11     int i,j=e;
12     while(U->root[j]==0)
13     {
14         //printf("parent[%d]=%d root=%d\n",j,U->parent[j],U->root[j]);
15         j=U->parent[j];
16     }
17     while(j!=e)
18     {
19         i=U->parent[e];
20         U->parent[e]=j;
21         e=i;
22     }
23     return j;
24 }
25 int UFunion(int i,int j,UFset U)
26 {
27     if(U->parent[i]<U->parent[j])
28     {
29         U->parent[j]+=U->parent[i];
30         U->root[i]=0;
31         U->parent[i]=j;
32         return j;
33     }
34     else
35     {
36         U->parent[i]+=U->parent[j];
37         U->root[j]=0;
38         U->parent[j]=i;
39         return i;
40     }
41 }
42 int main()
43 {
44     UFset UF;
45     UF=(UFset)malloc(sizeof(UFS));
46     int e,n,m,k,x,i,a,b,t1,t2;
47     scanf("%d %d %d",&n,&m,&k);
48     for(e=1;e<=n+1;e++)
49     {
50         UF->parent[e]=1;
51         UF->root[e]=1;
52     }
53     for(i=0;i<m;i++)
54     {
55         scanf("%d %d",&a,&b);
56         t1=UFfind(a,UF);t2=UFfind(b,UF);
57         if(t1!=t2)
58         {
59             UFunion(t1,t2,UF);
60         }
61     }
62     for(i=0;i<k;i++)
63     {
64         scanf("%d",&x);
65         printf("%d\n",UF->parent[UFfind(x,UF)]);
66     }
67     return 0;
68 }
View Code

并查集简单又好用

posted @ 2013-12-02 00:18  陈泽泽  阅读(202)  评论(0编辑  收藏  举报