-
Notifications
You must be signed in to change notification settings - Fork 2
/
graph3paint.cpp
66 lines (57 loc) · 2.13 KB
/
graph3paint.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
#include <iostream>
#include <vector>
bool check(size_t cur, char color, std::string& colors, std::vector<std::vector<size_t>>& graph, std::vector<bool>& checked, std::string& new_colors) {
checked[cur] = true;
if (color == colors[cur])
return false;
char temp = new_colors[cur];
new_colors[cur] = color;
bool is_check = true;
for (const auto& neig : graph[cur]) {
if (checked[neig]) {
if (new_colors[neig] == color) is_check = false;
continue;
}
char new_color = 'R';
if (colors[neig] != 'B' && color != 'B') {
new_color = 'B';
}
else if (colors[neig] == color || colors[neig] == 'R' && color == 'B' ||
colors[neig] == 'B' && color == 'R') {
new_color = 'G';
}
if (colors[neig] != color){
bool check_result = check(neig, new_color, colors, graph, checked, new_colors);
if (!check_result)
is_check = false;
}
}
if (!is_check) new_colors[cur] = temp;
return is_check;
}
bool main_check(size_t cur, char color, std::string& colors, std::vector<std::vector<size_t>>& graph, std::string& new_colors) {
std::vector<bool> checked(new_colors.size(), 0);
return check(cur, color, colors, graph, checked, new_colors);
}
int main() {
size_t n, m, start, end;
std::cin >> n >> m;
std::string colors;
std::cin >> colors;
std::vector<std::vector<size_t>> graph(n, std::vector<size_t>());
for (; m > 0; --m) {
std::cin >> start >> end;
graph[end - 1].push_back(start - 1);
graph[start - 1].push_back(end - 1);
}
std::string new_colors(n, ' ');
for (size_t i = 0; i < n; ++i) {
(new_colors[i] != ' '
|| main_check(i, 'R', colors, graph, new_colors)
|| main_check(i, 'G', colors, graph, new_colors)
|| main_check(i, 'B', colors, graph, new_colors));
}
if (new_colors.find(' ') != std::string::npos) std::cout << "Impossible";
else std::cout << new_colors;
return 0;
}