1804E - Routing - CodeForces Solution


bitmasks dp graphs

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define X first
#define Y second

using namespace std;
typedef long long llint;

const int maxn = 30;
const int base = 31337;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
const int logo = 20;
const int off = 1 << logo;
const int treesiz = off << 1;

int n, m;
vector< int > graph[maxn];
bool good[treesiz];
int dp[maxn][treesiz];
int ans[maxn];

int f(int x, int mask, int mini) {
	int &ret = dp[x][mask];
	if (ret != -1) return ret;

	ret = -2;
	for (int tren : graph[x]) {
		if (tren < mini) continue;
		if (tren == mini) {
			if (good[mask]) ret = mini;
		}
		if (mask & (1 << tren)) continue;
		if (f(tren, mask | (1 << tren), mini) != -2) ret = tren;
	}
	return ret;
}

int main() {
	scanf("%d%d", &n, &m);
	for (int i = 0; i < m; i++) {
		int a, b;
		scanf("%d%d", &a, &b); a--, b--;

		graph[a].push_back(b);
		graph[b].push_back(a);
	}

	int lim = (1 << n);
	for (int mask = 0; mask < lim; mask++) {
		bool flag = true;
		for (int i = 0; i < n; i++) {
			if (mask & (1 << i)) continue;
			bool tflag = false;
			for (int tren : graph[i]) {
				if (mask & (1 << tren)) tflag = true;
			}
			if (!tflag) flag = false;
		}
		good[mask] = flag;
	}

	for (int i = 0; i < n; i++)
		for (int j = 0; j < lim; j++) dp[i][j] = -1;

	int sol = -2;
	for (int i = 0; i < n; i++) {
		if (f(i, 1 << i, i) != -2) sol = i;
	}

	if (sol == -2) printf("No\n");
	else {
		printf("Yes\n");
		int stat = sol;

		int cp = stat;
		int mask = 1 << sol;
		//printf("debug: %d\n", sol.X);
		while (true) {
			//printf("tren: %d %d\n", stat, mask);
			ans[stat] = dp[stat][mask];
			int nex = dp[stat][mask];
			if (nex == cp) break;
			//system("pause");

			stat = nex;
			mask |= (1 << nex);
		}

		for (int i = 0; i < n; i++) {
			if (mask & (1 << i)) continue;
			for (int tren : graph[i]) {
				if (mask & (1 << tren)) ans[i] = tren;
			}
		}

		for (int i = 0; i < n; i++) printf("%d ", ans[i] + 1);
		printf("\n");
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1684C - Column Swapping
57C - Array
1713D - Tournament Countdown
33A - What is for dinner
810A - Straight A
1433C - Dominant Piranha
633A - Ebony and Ivory
1196A - Three Piles of Candies
299A - Ksusha and Array
448B - Suffix Structures
1092B - Teams Forming
1166C - A Tale of Two Lands
544B - Sea and Islands
152B - Steps
1174D - Ehab and the Expected XOR Problem
1511A - Review Site
1316A - Grade Allocation
838A - Binary Blocks
1515D - Phoenix and Socks
1624D - Palindromes Coloring
1552F - Telepanting
1692G - 2Sort
1191A - Tokitsukaze and Enhancement
903A - Hungry Student Problem
52B - Right Triangles
1712A - Wonderful Permutation
1712D - Empty Graph
1712B - Woeful Permutation
1712C - Sort Zero
1028B - Unnatural Conditions