首页 > 代码库 > UVA 1160 - X-Plosives

UVA 1160 - X-Plosives

题目地址

并查集

 1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 const int Nmax=1e5+10; 5 int f[Nmax]; 6 int a,b; 7 int ans; 8  9 10 void init()11 {12     ans=0;13     for(int i=0;i<Nmax;i++)14         f[i]=i;15 }16 17 int find(int x)18 {19     if(f[x]!=x)20         f[x]=find(f[x]);21     return f[x];22 }23 24 int merge(int a,int b)25 {26     int r1=find(a),r2=find(b);27     if(r1!=r2)28     {29         f[r1]=r2;30         return 1;31     }32     return 0;33 }34 35 int main()36 {37     while(scanf("%d",&a)!=EOF)38     {39         if(a==-1)40         {41             printf("0\n");42             continue;43         }44         scanf("%d",&b);45         init();46         if(!merge(a,b))47             ans++;48         while(1)49         {50             scanf("%d",&a);51             if(a==-1)52                 break;53             scanf("%d",&b);54             if(!merge(a,b))55                 ans++;56         }57         printf("%d\n",ans);58     }59     return 0;60 }

 

UVA 1160 - X-Plosives