From 191e37ed2e098167c5dd704caefcf6d9aa73a014 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Sun, 19 Jul 2020 21:47:57 -0500 Subject: Bipartite check done! --- Sources/GraphAlgo.cpp | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/Sources/GraphAlgo.cpp b/Sources/GraphAlgo.cpp index 7385763..71ed2c2 100644 --- a/Sources/GraphAlgo.cpp +++ b/Sources/GraphAlgo.cpp @@ -7,8 +7,14 @@ using std::vector; using std::queue; -void bfs(vector> &adj, int s, vector &dist) { +bool bfsBipartiteCheck(vector> &adj, int s) { + if (adj[s].size() == 0) + return true; + + vector dist(adj.size(), -1); + dist[s] = 0; queue vertexQ; + vertexQ.push(s); while (!vertexQ.empty()) { @@ -17,19 +23,23 @@ void bfs(vector> &adj, int s, vector &dist) { for (int i : adj[u]) { if (dist[i] == -1) { vertexQ.push(i); - dist[i] = dist[u] + 1; - } + if (dist[u] == 0) + dist[i] = 1; + if (dist[u] == 1) + dist[i] = 0; + } else if (dist[i] == dist[u]) + return false; } } + return true; } -int distance(vector > &adj, int s, int t) { - vector dist(adj.size(), -1); - dist[s] = 0; - - bfs(adj, s, dist); - - return dist[t]; +int bipartite(vector > &adj) { + bool bipartiteCheckNodes = bfsBipartiteCheck(adj, 0); + if (bipartiteCheckNodes) + return 1; + else + return 0; } int main() { @@ -42,10 +52,7 @@ int main() { adj[x - 1].push_back(y - 1); adj[y - 1].push_back(x - 1); } - int s, t; - std::cin >> s >> t; - s--, t--; - std::cout << distance(adj, s, t); + std::cout << bipartite(adj); } //TEST(Acyclicity, ac1) { -- cgit v1.2.3