CSES - BAPC 2015 - Results
Submission details
Task:Map Colouring
Sender:Antti Röyskö
Submission time:2017-10-17 21:53:33 +0300
Language:C++
Status:READY
Result:
Test results
testverdicttime
#10.16 sdetails

Code

#include <iostream>
#include <vector>

int n, m;
std::vector<std::vector<int>> conns;
std::vector<int> color;
std::vector<bool> handled;

bool tryall (int i) {
	if (handled[i]) return true;
	int orig = color[i];
	if (orig == 0) return false;
	handled[i] = true;
	bool can = true;
	for (int j = 1; j < 8; j <<= 1) {
		if (orig & j) {
			for (int t = 0; t < n; ++t) {
				if (conns[i][t]) {
					color[t] &= 7 - j;
					bool sub = tryall(t);
					if (! sub) {
						can = false;
					}
				}
			}
		}
	}
	handled[i] = false;
	return can;
}

bool test() {
	for (int i = 0; i < n; ++i) {
		if (!tryall(i)) return false;
	}
	return true;
}

bool bipartite() {
	std::vector<bool> part (n);
	for (int i = 0; i < n; ++i) {
		for (int j = i+1; j < n; ++j) {
			if (conns[i][j]) part[j] = !part[i];
		}
	}
	for (int i = 0; i < n; ++i) {
		for (int j = i+1; j < n; ++j) {
			if (conns[i][j]) {
				if (part[j] == part[i]) return false;
			}
		}
	}
	return true;
}

void solve() {
	std::cin >> n >> m;
	conns.clear();
	conns.resize(n*n);
	color.clear();
	color.resize(n);
	handled.clear();
	handled.resize(n);
	for (int i = 0; i < n; ++i) {
		handled[i] = false;
	}
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			conns[i][j] = 0;
		}
	}
	for (int i = 0; i < m; ++i) {
		int a, b;
		std::cin >> a >> b;
		--a; --b;
		conns[a][b] = 1;
		conns[b][a] = 1;
	}
	if (m == 0) {
		std::cout << "1\n";
	} else if (bipartite()) {
		std::cout << "2\n";
	} else if (test()) {
		std::cout << "3\n";
	} else {
		bool can = false;
		for (int a = 0; (!can) && (a < n); ++a) {
			handled[a] = true;
			if (test()) {
				can = true;
			}
			for (int b = a+1; (!can) && (b < n); ++b) {
				if (conns[a][b]) continue;
				handled[b] = true;
				if (test()) {
					can = true;
				}
				for (int c = b+1; (!can) && (c < n); ++c) {
					if (conns[a][c] || conns[b][c]) continue;
					handled[c] = true;
					if (test()) {
						can = true;
					}
					for (int d = c+1; (!can) && (d < n); ++d) {
						if (conns[a][d] || conns[b][d] || conns[c][d]) continue;
						handled[d] = true;
						if (test()) {
							can = true;
						}
						handled[d] = false;
					}
					handled[c] = false;
				}
				handled[b] = false;
			}
			handled[a] = false;
		}
	}
}


int main() {
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(0);

	int T;
	std::cin >> T;
	for (int i = 0; i < T; ++i) {
		solve();
	}
}

Test details

Test 1

Verdict:

input
33
4 0
4 4
0 1
1 2
...

correct output
1
2
many
4
1
...

user output
(empty)