1. 程式人生 > >*step3_資料結構_ACM並查集 HDU1272 小希的迷宮【並查集】

*step3_資料結構_ACM並查集 HDU1272 小希的迷宮【並查集】

瘋狂WA題。

這道題就是一個簡單的並查集。

但是我在瘋狂WA題的過程中,個人覺得這道題還有點問題,首先,這道題沒有說清楚,有沒有對同一條邊輸入兩次的情況,在第一遍wa掉後,我打算解決這個問題,顯然,無果,因為測試資料沒那種情況。

在這道題應當收穫的教訓是,對這種簡單題,第一遍wa掉之後,首先應當對極點進行測試。即對空情況進行判斷。!!

#include<iostream>
#include<set>
#include<vector>
using namespace std;
bool ifhuan=false;
const int maxn=100005;
int p[maxn];
bool mark[maxn];
int find(int x){//搜尋演算法
	if(p[x]==x)return p[x];
	int t=find(p[x]);
	p[x]=t;
	return t;
}
void un(int x,int y){
	int t1=find(x);
	int t2=find(y);
	if(t1!=t2){
	  p[t1]=t2;
	}else{
		ifhuan=true;
	}
}

int main(){	
	int a,b;
	while(cin>>a>>b&&(a!=-1||b!=-1)){
		if(a==0&&b==0){
			cout<<"Yes"<<endl;
			continue;
		}
		
		
		for(int i=0;i<=maxn;i++){
			p[i]=i;mark[i]=false;
		}		
		ifhuan=false;
		while(a!=0||b!=0){
			un(a,b);
			mark[a]=mark[b]=true;
			cin>>a>>b;
		}		
		int num=0;
		for(int i=0;i<=maxn;i++){
			if(mark[i]&&p[i]==i)num++;
		} 
		if(ifhuan==false&&num==1)cout<<"Yes"<<endl;
		else cout<<"No"<<endl;	
	}	
	return 0;
}