POJ 2492 A Bug's Life(扩展并查集)

#pragma warning(disable:4996)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

//扩展并查集
int fa[2001], relation[2001];
//同性为0,异性为1

int find(int x){
	if (x == fa[x])return x;
	int tmp = fa[x];
	fa[x] = find(tmp);
	relation[x] = (relation[x] + relation[tmp]) % 2;
	return fa[x];
}

void merge(int x, int y){
	int fx = find(x);
	int fy = find(y);
	if (fx == fy)return;

	fa[fx] = fy;
	relation[fx] = (relation[x] + relation[y] == 1) ? 0 : 1;

}

int main(){
	int t;
	scanf("%d", &t);
	for (int kase = 1; kase <= t; kase++){

		memset(relation, 0, sizeof relation);
		for (int i = 1; i < 2001; i++)fa[i] = i;
		string ans = "";
		int n, m;
		scanf("%d %d", &n, &m);
		for (int i = 1; i <= m; i++){
			int x, y;
			scanf("%d %d", &x, &y);

			if (find(x) == find(y)){
				if (relation[x] == relation[y])
					ans = "Suspicious bugs found!";
			}
			else{
				merge(x, y);
			}

		}
		if (ans.size() > 0){
			cout << "Scenario #" << kase << ':' << endl << ans << endl << endl;
		}
		else{
			cout << "Scenario #" << kase << ':' << endl << "No suspicious bugs found!" << endl << endl;
		}

	}
	return 0;
}

你可能感兴趣的:(POJ 2492 A Bug's Life(扩展并查集))