summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp
blob: dfd74e167fcd398b3bf44c1c44f7cb6a084dc6cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <vector>
#include <queue>

using std::vector;
using std::queue;

int bipartite(vector<vector<int> > &adj) {
  vector<int> t(adj.size(), -1);

  queue<int> q;
  q.push(0);
  t[0] = 0;

  int tag = 1;
  while (!q.empty()) {
      int v = q.front();
      /* std::cout << " check : " << v << " tag " << tag << std::endl; */
      q.pop();
      tag = !t[v];
      for (int i = 0; i < adj[v].size(); i++) {
          int w = adj[v][i];
          /* std::cout << "   " << w  << " " << t[w] << std::endl; */
          if (t[w] == -1) {
              q.push(w);
              t[w] = tag;
          } else if (t[w] != tag) {
              /* std::cout << "   wrong " << w  << " " << t[w] << std::endl; */
              return 0;
          }
      }
  }
  return 1;
}

int main() {
  int n, m;
  std::cin >> n >> m;
  vector<vector<int> > adj(n, vector<int>());
  for (int i = 0; i < m; i++) {
    int x, y;
    std::cin >> x >> y;
    adj[x - 1].push_back(y - 1);
    adj[y - 1].push_back(x - 1);
  }
  std::cout << bipartite(adj) << '\n';
}