Disjoint-set maze of small Greek hdu-1272

Title Description

Determining an undirected graph is not a tree
Alt

Input

Input data comprises a plurality of sets, each set of data is an integer of 00 to the end of the list, it 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 data inputs, the output comprises only one row. If the idea of ​​the labyrinth in line with little hope, then the output "Yes", otherwise a "No".

sample input
6 8  5 3  5 2  6 4
5 6  0 0

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

Thinking

Determining a tree, undirected graph, like note the following:
1, only one root
2, when a sub-node number as a number of other, they do not have the same parent node

Code also comment on ideas

#include<bits/stdc++.h>
using namespace std;

int f[100010];       //记录父结点
bool v[100010];        //标记,待会用来数根的

int find(int x) {        //路径压缩
	return x==f[x]?x:f[x]=find(f[x]);
}

void unions(int x, int y) {
	int fx=find(x);
	int fy=find(y);
	if ( fx!=fy ) f[fx]=fy;
}

int main() {
	int x,y;
	while(1) {
		int x,y;
		bool flag=1;
		for(int i=1; i<=100000; i++ ) {
			f[i]=i,v[i]=0;
		}
		while(~scanf("%d %d",&x,&y)) {
			if ( x==-1 && y==-1 ) return 0;
			if ( x==0 && y==0 ) break;
			if ( flag==0 ) continue;
			if ( find(x)==find(y) && x!=y ) {       //这里就是注意点2
				flag=0;continue;
			}
			unions(x,y);
			v[x]=v[y]=1;
		}
		int root=0;
		for(int i=1; i<=100000; i++ ) {         //注意点1,判断根数
			if ( v[i] && i==find(i) ) root++;
			if ( root>1 ) flag=0;
		}
		if ( flag ) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}
Published 13 original articles · won praise 6 · views 581

Guess you like

Origin blog.csdn.net/zx1020354953/article/details/104103668