CodeForces 1228D Complete Tripartite

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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1, M = 3e5;
int n, m, a, b, h[N], e[M], ne[M], idx, color[N], cnt[3];
void add(int u, int v) {
e[idx] = v, ne[idx] = h[u], h[u] = idx++;
}
int main() {
memset(h, -1, sizeof(h));
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
scanf("%d%d", &a, &b);
a < b ? add(a, b) : add(b, a);
}
bool invalid = false;
fill(color + 1, color + 1 + n, 1);
cnt[0] = n;
for (int u = 1; u <= n; ++u) {
for (int cu = color[u], i = h[u]; ~i; i = ne[i]) {
int v = e[i], &cv = color[v];
if (cv == cu) {
if (cv == 1) cv = 2, --cnt[0], ++cnt[1];
else if (cv == 2) cv = 3, --cnt[1], ++cnt[2];
else {
invalid = true;
break;
}
}
}
if (invalid) break;
}
if (invalid ||
cnt[0] * cnt[1] + cnt[0] * cnt[2] + cnt[1] * cnt[2] != m ||
!cnt[0] || !cnt[1] || !cnt[2])
puts("-1");
else
for (int i = 1; i <= n; ++i)
printf("%d%c", color[i], i < n ? ' ' : '\n');
return 0;
}