判断是否为二分图

Google CodeJam China Campus Test 2014

Practice Round Problem A: https://code.google.com/codejam/contest/2933486/dashboard#s=p0


Solution:

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>

using namespace std;

inline int getNode(const string &name, int &n, map<string, int> &hash, vector<set<int> > &adj) {
	const map<string,int>::iterator it = hash.find(name);
	if (it != hash.end())
		return it->second;
	adj.push_back(set<int> ());
	const int node = n++;
	hash[name] = node;
	return node;
}

bool check(const int n, const vector<set<int> > &adj) {
	const int BLACK = -1, WHITE = 1, UNCOLORED = 0;
	vector<int> color(n, UNCOLORED);
	for (int i = 0; i < n; ++i) {
		if (color[i]) continue;
		color[i] = BLACK;
		queue<int> q;
		q.push(i);
		while (!q.empty()) {
			const int u = q.front();
			q.pop();
			for (set<int>::iterator it = adj[u].begin(); it != adj[u].end(); ++it) {
				const int v = (*it);
				if (color[v] == color[u]) return false;
				if (color[v]) continue;
				color[v] = -color[u];
				q.push(v);
			}
		}
	}
	return true;
}

int main() {
	int t;
	cin >> t;
	for (int testcase = 1; testcase <= t; ++testcase) {
		int m, n = 0;
		cin >> m;
		map<string, int> hash;
		vector<set<int> > adj;
		while (m--) {
			string a, b;
			cin >> a >> b;
			const int u = getNode(a, n, hash, adj), v = getNode(b, n, hash, adj);
			adj[u].insert(v);
			adj[v].insert(u);
		}
		cout << "Case #" << testcase << ": ";
		if (check(n, adj))
			cout << "Yes\n";
		else
			cout << "No\n";
	}
	return 0;
}



References:

http://blog.163.com/kevinlee_2010/blog/static/1698208202011113054046645/

http://dsqiu.iteye.com/blog/1689505

http://hi.baidu.com/follvsfdgrbhlsq/item/ab10a9369c612684b611db78


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值