Codeforces 935E Fafa and Ancient Mathematics dp

时间:2022-10-22 19:34:38

Fafa and Ancient Mathematics

转换成树上问题dp一下。

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ull unsigned long long using namespace std; const int N = 1e4 + ;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + ;
const double eps = 1e-;
const double PI = acos(-); char s[N];
int P, M, n, ans;
int mxdp[N][], mndp[N][], cnt[N];
int weight[N]; inline bool chkmax(int &a, int b) {
return a < b ? a = b, true : false;
}
inline bool chkmin(int &a, int b) {
return a > b ? a = b, true : false;
} int getPos(int l, int r) {
int w = , pos = -;
int digit = -;
for(int i = l; i <= r; i++) {
if(s[i] == '(') w += ;
else if(s[i] == ')') w -= ;
else if(s[i] == '?') weight[i] = w;
if(isdigit(s[i])) digit = i;
}
for(int i = l; i <= r; i++) {
if(s[i] == '?') {
if(pos == - || weight[pos] > weight[i]) pos = i;
}
}
if(~pos) return pos;
return digit;
} void dfs(int l, int r, int rt) {
if(s[rt] != '?') {
mxdp[rt][] = s[rt] - '';
mndp[rt][] = s[rt] - '';
return;
}
int ls = getPos(l, rt - );
int rs = getPos(rt + , r);
dfs(l, rt - , ls);
dfs(rt + , r, rs);
cnt[rt] = cnt[ls] + cnt[rs] + ;
if(P < M) {
for(int i = ; i <= cnt[ls]; i++) {
for(int j = ; j <= cnt[rs]; j++) {
if(i + j > P) continue;
if(P - i - j > ) {
chkmax(mxdp[rt][i + j + ], mxdp[ls][i] + mxdp[rs][j]);
chkmin(mndp[rt][i + j + ], mndp[ls][i] + mndp[rs][j]);
}
if(M - (cnt[ls] - i) - (cnt[rs] - j) > ) {
chkmax(mxdp[rt][i + j], mxdp[ls][i] - mndp[rs][j]);
chkmin(mndp[rt][i + j], mndp[ls][i] - mxdp[rs][j]);
}
}
}
} else {
for(int i = ; i <= cnt[ls]; i++) {
for(int j = ; j <= cnt[rs]; j++) {
if(i + j > M) continue;
if(M - i - j > ) {
chkmax(mxdp[rt][i + j + ], mxdp[ls][i] - mndp[rs][j]);
chkmin(mndp[rt][i + j + ], mndp[ls][i] - mxdp[rs][j]);
}
if(P - (cnt[ls] - i) - (cnt[rs] - j) > ) {
chkmax(mxdp[rt][i + j], mxdp[ls][i] + mxdp[rs][j]);
chkmin(mndp[rt][i + j], mndp[ls][i] + mndp[rs][j]);
}
}
}
}
} int main() {
scanf("%s", s + );
n = strlen(s + );
scanf("%d%d", &P, &M);
for(int i = ; i <= n; i++)
for(int j = ; j <= min(P, M); j++)
mxdp[i][j] = -inf, mndp[i][j] = inf;
int root = getPos(, n);
dfs(, n, root);
printf("%d\n", mxdp[root][min(P, M)]);
return ;
} /*
*/