andmej / acm

My solutions for problems from the UVa Online Judge (Valladolid).

acm / 10004 - Bicoloring / 10004.2.cpp
100644 45 lines (37 sloc) 0.902 kb
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
/*
Problem: 10004 - Bicoloring (UVa online judge)
 
Author: Andrés Mejía-Posada (http://github.com/andmej/acm)
Algorithm: Depth-first search
*/
#include <iostream>
#include <vector>
 
using namespace std;
 
bool dfs(int u, int c, int * color, vector<int> * g){
  //printf("u = %d, c = %d, color[%d] = %d\n", u, c, u, color[u]);
  if (color[u] != 0) return (c == color[u]);
 
  color[u] = c;
  for (int i=0; i<g[u].size(); ++i){
    int nc = (c == 1 ? 2 : 1);
    if (dfs(g[u][i], nc, color, g) == false){
      return false;
    }
  }
  return true;
}
 
int main(){
  int n, l;
  while (cin >> n && n){
    cin >> l;
    vector<int> g[n];
    int color[n];
    memset(color, 0, sizeof color);
 
    while (l--){
      int u, v;
      cin >> u >> v;
      g[u].push_back(v);
      g[v].push_back(u);
    }
 
    cout << (dfs(0, 1, color, g) ? "" : "NOT ") << "BICOLORABLE." << endl;
  }
  return 0;
}