并查集:
#includeusing namespace std;const int cityNum = 1000 ;int city[cityNum];int N,M;int total;void init(){ for(int i=1;i<=N;i++){ city[i] = i; }}int findSet(int x){ int tmp = x; do{ tmp = city[tmp]; }while(tmp != city[tmp]); city[x] = tmp; return tmp;}void unionSet(int x,int y){ //Y->X int xP = findSet(x); int yP = findSet(y); if(xP != yP){ total--; city[yP] = xP; city[y] = xP; }}int main(){ int city1,city2; while(scanf("%d %d",&N,&M) && N){ total = N-1; init(); for(int i=0;i