forked from ksaveljev/UVa-online-judge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10004.cpp
105 lines (88 loc) · 1.74 KB
/
10004.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <map>
#include <vector>
#include <queue>
using namespace std;
struct Vertex
{
public:
int id;
int color;
vector<Vertex*> adj;
Vertex (int id) : id(id) { color = -1; }
};
typedef map<int, Vertex*> vmap;
typedef pair<int, Vertex*> vpair;
class Graph
{
public:
Graph() {}
~Graph();
void addEdge (int begin, int end, bool directed);
bool bicolor(Vertex* v, int color);
Vertex* firstVertex();
private:
Vertex* getVertex (int v);
vmap vertexMap;
vector<Vertex*> allVertexes;
};
Graph::~Graph()
{
for (int i = 0; i < allVertexes.size(); i++)
delete allVertexes[i];
}
void Graph::addEdge (int begin, int end, bool directed = false)
{
Vertex* v = getVertex (begin);
Vertex* w = getVertex (end);
v->adj.push_back (w);
if (!directed)
w->adj.push_back (v);
}
Vertex* Graph::getVertex (int v)
{
vmap::iterator it = vertexMap.find (v);
if (it == vertexMap.end()) {
Vertex* newv = new Vertex (v);
allVertexes.push_back (newv);
vertexMap.insert (vpair (v, newv));
return newv;
}
return (*it).second;
}
Vertex* Graph::firstVertex()
{
return allVertexes[0];
}
bool Graph::bicolor(Vertex* v, int color)
{
bool result = true;
if (v->color == -1) {
v->color = color;
for (int i = 0; i < v->adj.size(); i++) {
result = bicolor(v->adj[i], (color + 1) % 2);
if (!result) break;
}
} else {
if (v->color != color)
result = false;
}
return result;
}
int main (void) {
int nodes, edges, a, b;
while (cin >> nodes) {
if (nodes == 0) break;
cin >> edges;
Graph* g = new Graph();
while (edges--) {
cin >> a >> b;
g->addEdge (a,b);
}
if (g->bicolor(g->firstVertex(), 0))
cout << "BICOLORABLE." << endl;
else
cout << "NOT BICOLORABLE." << endl;
delete g;
}
}