题解:G. Game on Chessboard

题解:G. Game on Chessboard_第1张图片

 

#include 

using namespace std;
#define OST ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define ll long long
#define endl "\n"
const ll mod = 1e9 + 7, N = (1 << 24) + 5;
string a[13];
ll w[13][13];
ll dp[N];
void solve() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i ++) cin >> a[i];
	for (int i = 0; i < n; i ++)
		for (int j = 0; j < n; j++) cin >> w[i][j];
	ll sta = (1 << n) - 1;
	ll end = sta << n;
	for (int i = 0; i < N; i ++) dp[i] = mod;
	dp[end] = 0;
	for (int s = end; s >= sta; s --) {
		if (dp[s] == mod) continue;
		// 0表示向左走,1表示向右走
		// 从左上走到右下应该要n个1, n个0
		int cnt = 0;
		for (int i = 0; i <= 2 * n; i ++) {
			if (s >> i & 1) cnt ++;
		}
		if (cnt != n) continue;
		int x = - 1, y = 0;
		for (int i = 2 * n - 1; i >= 1; i --) {
			if (s >> i & 1) {
				x ++;
			} else {
				y ++;
			}
			if (s >> i & 1 && !(s >> (i - 1) & 1)) {
				//直接拿掉
				if (a[x][y] == '.')
					dp[s - (1 << (i - 1))] = min(dp[s - (1 << (i - 1))], dp[s]);
				else
					dp[s - (1 << (i - 1))] = min(dp[s - (1 << (i - 1))], dp[s] + w[x][y]);
				// 找一下下一个点然后一起拿掉
				int nx = -1, ny = 0;
				for (int j = 2 * n - 1; j > i + 1; j --) {
					if (s >> j & 1) nx ++;
					else ny ++;
					if (s >> j & 1 && !(s >> (j - 1) & 1)) {
						// cout << nx << " " << ny << endl;
						if (a[x][y] == 'B' && a[nx][ny] == 'W') {
							dp[s - (1 << (i - 1)) - (1 << (j - 1))] = min(dp[s - (1 << (i - 1)) - (1 << (j - 1))], dp[s] + abs(w[x][y] - w[nx][ny]));
						}
						if (a[x][y] == 'W' && a[nx][ny] == 'B') {
							dp[s - (1 << (i - 1)) - (1 << (j - 1))] = min(dp[s - (1 << (i - 1)) - (1 << (j - 1))], dp[s] + abs(w[x][y] - w[nx][ny]));
						}
					}
				}
			}
		}
	}
	cout << dp[sta] << endl;
}

signed main() {
	OST;
	int T = 1;
	// cin >> T;
	while (T--) { solve(); }
	return 0;
}

你可能感兴趣的:(算法题解,算法)