Posted in DSU

hdu 1272/ kuangbin 5-M(dsu)

10/17/2017
Problem: http://acm.split.hdu.edu.cn/showproblem.php?pid=1272
Solution: DSU. However, also need to check if all dots are connected. For that,
simply loop every dot that exists, and check if all their father are
the same.
Note: This problem would be much more easier if we consider the identity of a
tree, which is the number of dot is always one more than that of edges.
Link: https://prionanthaspace.wordpress.com/2017/10/18/hdu-1272-kuangbin-5-mgraph/


#include<iostream>
#include<string.h>
#include<cmath>
using namespace std;

int parent[100005] = {0};
int flag[100005] = {0};

int find(int a) {
	if (parent[a] == a) {
		return a;
	} else {
		return parent[a] = find(parent[a]);
	}
}

void merge(int a, int b) {
	int p1 = find(a);
	int p2 = find(b);
	if (p1 != p2) {
		parent[p1] = p2;
	}
}

int main() {
	int a, b;
	bool ans = true;
	int maxx = 0;
	int minn = 100005;
	for (int i = 1; i <= 100005; i++) {
		parent[i] = i;
	}	
	memset(flag, 0, sizeof(flag));
	while (cin >> a >> b) {
		if (a == -1 && b == -1) {
			return 0;
		} else if (!a && !b) {
			if (ans) {
				int tmp = find(minn);
				for (int i = minn + 1; i <= maxx; i++) {
					if (flag[i] && find(i) != tmp) {
						// cout << tmp << ' ' << find(i) << endl;
						ans = false;
						break;
					}
				}
			}		
			cout << (ans? "Yes" :"No") << endl;
			maxx = 0;
			minn = 100005;			
			ans = true;
			for (int i = 1; i <= 100005; i++) {
				parent[i] = i;
			}
			memset(flag, 0, sizeof(flag));
			continue;
		}
		minn = min(minn, min(a, b));
		maxx = max(maxx, max(a, b));
		flag[a] = 1;
		flag[b] = 1;
		if (find(a) != find(b)) {
			merge(a, b);
		} else {
			ans = false;
		}
	}
	return 0;
}

One thought on “hdu 1272/ kuangbin 5-M(dsu)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s