bzoj 1055 [HAOI2008]玩具取名 区间dp
题面
解法
直接区间dp即可
时间复杂度:\(O(16n^3)\)
代码
#include <bits/stdc++.h>
#define N 210
using namespace std;
struct Node {
int x, y;
} a[5][N];
int s[5], p[5][5][5];
bool f[N][N][5], vis[N][N][5];
int num(char ch) {
if (ch == 'W') return 1;
if (ch == 'I') return 2;
if (ch == 'N') return 3;
return 4;
}
bool dp(int l, int r, int k) {
if (r - l + 1 <= 2) return f[l][r][k];
if (vis[l][r][k]) return f[l][r][k];
vis[l][r][k] = 1;
for (int i = l; i < r; i++)
for (int j = 1; j <= s[k]; j++)
f[l][r][k] |= (dp(l, i, a[k][j].x) & dp(i + 1, r, a[k][j].y));
return f[l][r][k];
}
int main() {
for (int i = 1; i <= 4; i++) cin >> s[i];
for (int i = 1; i <= 4; i++)
for (int j = 1; j <= s[i]; j++) {
string st; cin >> st;
p[num(st[0])][num(st[1])][i] = 1;
a[i][j] = (Node) {num(st[0]), num(st[1])};
}
string st; cin >> st;
int len = st.size() - 1;
for (int i = 0; i <= len; i++) f[i][i][num(st[i])] = 1;
for (int i = 0; i < len; i++)
for (int j = 1; j <= 4; j++)
f[i][i + 1][j] = p[num(st[i])][num(st[i + 1])][j];
bool flag = false;
for (int i = 1; i <= 4; i++) {
f[0][len][i] = dp(0, len, i);
if (!f[0][len][i]) continue;
flag = true;
if (i == 1) cout << 'W';
if (i == 2) cout << 'I';
if (i == 3) cout << 'N';
if (i == 4) cout << 'G';
}
if (!flag) cout << "The name is wrong!\n";
return 0;
}