给你几组数a和b,表示a和b会形成化合物,如果有有超过3个物品互相形成化合物就会爆炸。这样的物品不能装上车,如果让你按照给出的顺序把这些物品装上车,有多少组不能够装上车? 输入格式:每行两个数,表示每个化合物的两个元素。以-1结束。 输出格式:不能装上车的化合物数量。
1 #include<cstdio> 2 using namespace std; 3 const int maxn=1111111; 4 int father[maxn]; 5 int find(int x) 6 { 7 if(father[x]!=x) father[x]=find(father[x]); 8 return father[x]; 9 } 10 void unionn(int r1,int r2) 11 { 12 father[r2]=r1; 13 } 14 15 int main() 16 { 17 int x,y,r1,r2,shu; 18 while(scanf("%d",&x)==1) 19 { 20 for(int i=1;i<=maxn;++i) father[i]=i; 21 shu=0; 22 while(x!=-1) 23 { 24 scanf("%d",&y); 25 r1=find(x); 26 r2=find(y); 27 if(r1!=r2) unionn(r1,r2); 28 else shu++; 29 scanf("%d",&x); 30 } 31 printf("%d\n",shu); 32 } 33 return 0; 34 }