UVA1160(並查集判斷強聯通分量)
阿新 • • 發佈:2018-11-08
https://cn.vjudge.net/problem/UVA-1160
只要該化合物的兩個分量已經屬於屬於同一強連通分量,化合物就不穩定,直接拒絕
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define maxn 500005 int father[maxn]; int find(int x) { if(father[x]!=x) father[x]=find(father[x]); return father[x]; } void unionn(int x,int y) { int r1=find(x); int r2=find(y); if(r1!=r2) father[r2]=r1; } int main() { int x,y; while(~scanf("%d",&x)) { if(x==-1) { printf("0\n"); continue; } int cnt=0; for(int i=0;i<maxn;i++) father[i]=i; while(x!=-1) { scanf("%d",&y); if(find(x)==find(y)) cnt++; else unionn(x,y); scanf("%d",&x); } printf("%d\n",cnt); } return 0; }