-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuva-11080.cpp
91 lines (73 loc) · 1.55 KB
/
uva-11080.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
//uva 11080
//Place the Guards
#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
int bipartite(vector < set <int> > & Graph, vector <bool> & visited, int start);
int main(void)
{
int T = 0;
cin >> T;
while(T--){
int v, e;
cin >> v >> e;
vector < set <int> > Graph(v);
for(int i = 0; i < e; ++i){
int x, y;
cin >> x >> y;
Graph[x].insert(y);
Graph[y].insert(x);
}
int minGuards = 0;
bool minGuardPossible = 1;
vector <bool> visited(v, false);
for(int i = 0; i < v; ++i)
if(!visited[i]){
int tmp = bipartite(Graph, visited, i);
if(tmp == -1){
minGuardPossible = 0;
break;
}
minGuards += tmp;
}
if(!minGuardPossible)
cout << "-1" << endl;
else
cout << minGuards << endl;
}
return 0;
}
int bipartite(vector < set <int> > & Graph, vector <bool> & visited, int start)
{
int n = Graph.size();
bool is_bipartite = 1;
int count0 = 1, count1 = 0;//start node is colored black
vector <bool> color(n, false);
queue <int> Queue;
visited[start] = 1;
Queue.push(start);
while(!Queue.empty()){
int front = Queue.front();
Queue.pop();
for(auto a : Graph[front])
if(visited[a] && color[a] == color[front])
is_bipartite = 0;
else if(!visited[a]){
color[a] = !color[front];
if(color[a]) ++count1;
else ++count0;
visited[a] = true;
Queue.push(a);
}
}
if(is_bipartite){
int result = min(count0, count1);
if(result)
return result;
else //case only one group exist
return max(count0, count1);
}
return -1;
}