Codeforces 354B 博弈, DP,记忆化搜索

题意:现在有一个字符矩阵,从左上角出发,每个人交替选择一个字符。如果最后字符a数目大于字符b,那么第一个人获胜,否则b获胜,否则平均。现在双方都不放水,问最后结果是什么?

思路:这题需要注意,选择的字符串不是一条单纯的路径,而是包括这个字符串的所有路径的并。

比如:

abc

bac

ccc

ab字符串其实是(1, 2)和(2, 1)的并,abc是(1, 3)和(3, 1)的并。

因为n最大只有20,那么对角线长度最长只有20,我们可以考虑状压,通过状压来更新状态,转移的时候枚举26个字母转移。

代码:

#include <bits/stdc++.h>
#define pii pair<int, int>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 20;
vector<pii> a[maxn * 2];
int id[maxn][maxn];
bool v[40][1 << 20];
int dp[40][1 << 20];
char s[25][25];
int n;
int cal(char ch) {
	if(ch == 'a') return 1;
	else if(ch == 'b') return -1;
	return 0;
}
int dfs(int deep, int mask) {
	if(deep == n * 2 - 2) return 0;
	if(v[deep][mask]) return dp[deep][mask];
	int sz = a[deep].size(); 
	int ans;
	if(deep & 1) ans = -INF;
	else ans = INF;
	for (char c = 'a'; c <= 'z'; c++) {
		int add = cal(c);
		int Next_mask = 0;
		for (int j = 0; j < sz; j++) {
			if((mask >> j) & 1) {
				pii tmp = a[deep][j];
				int x = tmp.first, y = tmp.second;
				if(x < n - 1 && s[x + 1][y] == c)
					 Next_mask |= (1 << id[x + 1][y]);
				if(y < n - 1 && s[x][y + 1] == c)
					 Next_mask |= (1 << id[x][y + 1]);
			}
		}
		if(Next_mask) {
			if(deep & 1) ans = max(ans, add + dfs(deep + 1, Next_mask));
			else ans = min(ans, add + dfs(deep + 1, Next_mask));
		}
	}
	v[deep][mask] = 1;
	dp[deep][mask] = ans;
	return ans;
}
int main() {
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%s", s[i]);
	}
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++) {
			id[i][j] = a[i + j].size();
			a[i + j].push_back(make_pair(i, j));
		}
	int ans = dfs(0, 1);
	ans += cal(s[0][0]);
	if(ans > 0) printf("FIRST
");
	else if(ans < 0) printf("SECOND
");
	else printf("DRAW
");
} 

  

原文地址:https://www.cnblogs.com/pkgunboat/p/11110385.html