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