Little hope maze HDU - 1272 --- disjoint-set + thinking

Last Gardon maze castle little hope to play for a long time (see Problem B), and now she wanted to design a maze Gardon to let go. But she maze design ideas are not the same, she thought first of all of the channels should be two-way communication, that is if there is a passage room A and B, then both went to the room from the room A through B it can also be it went through the room a from the room B, to raise the difficulty, any small hope hope the two rooms has one and only one path can communicate (unless go back now). Little hope now her design to you, let you help her determine whether the design of her design ideas. For example the following example, the first two are eligible, but there are two ways to the final arrival 8 from 5.
Here Insert Picture Description

Input
Input data comprising a plurality of sets, each set of data is an integer of 00 to the end of the list, indicates the number of two rooms a channel connection. No room is at least 1 and not more than 100,000. A blank line between each two sets of data.
Two end in the entire file 1.
Output
For each set of input data, output comprises only one row. If the idea of the labyrinth in line with little hope, then the output "Yes", otherwise a "No".
The Input the Sample
. 6 2. 8. 6. 5. 4. 3. 5
. 5 0 0. 6

8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0

3 8 6 8 6 4
5 3 5 6 5 2 0 0

-1 -1
Sample Output
Yes
Yes
No

Analysis: If a tree is given no weight and side. Yes output, otherwise the output No
tree must satisfy two conditions: there is only one link component, and any two paths that can not reach
if there are two paths through the two points as long as the communication to see whether the determination between any two points In addition there will be a side insert? ?

With disjoint-set maintenance. If the two points are in communication component appears, it will constitute two paths.


#include<iostream>
#include<set>
#include<algorithm>
#include<cstdio>
using namespace std;
const int N=1e5+1000;
int fa[N];
int u,v;
int find(int x)
{
	if(x!=fa[x]) return fa[x]=find(fa[x]);
	return fa[x]; 
}
bool  build(int u,int v)
{
	int x=find(u);
	int y=find(v);
	if(x!=y)
	{
		fa[x]=y;
		return true;
	}
	return false;
}
int main()
{
	while(~scanf("%d %d",&u,&v)&&u!=-1&&v!=-1)
	{
		for(int i=0;i<N;i++) fa[i]=i;
		set<int> s;
		bool f=true;
		if(u==0&&v==0)
		{
			cout<<"Yes"<<endl;
			continue; 
		}
		do
		{
			if(!build(u,v)) f=false;
			s.insert(u);
			s.insert(v);
		}while(scanf("%d %d",&u,&v)&&u!=0&&v!=0);
		if(f)
		{
			int cnt=0; //记录连通分量个数
			for(set<int>::iterator it=s.begin();it!=s.end();it++)
			{
				if(*it==find(*it)) cnt++;
			}
			if(cnt>1) f=false;  //要求只有一个连通分量
		}
		if(f) puts("Yes");
		else puts("No");
	}
}
Published 309 original articles · won praise 6 · views 5273

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/104066645