1. 程式人生 > >Codeforces 935E Fafa and Ancient Mathematics dp

Codeforces 935E Fafa and Ancient Mathematics dp

scanf const continue int nbsp ont esp clu void

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 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); char s[N]; int P, M, n, ans; int mxdp[N][101], mndp[N][101], 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 = 0, pos = -1; int digit = -1; for(int i = l; i <= r; i++) { if(s[i] == () w += 10000; else
if(s[i] == )) w -= 10000; 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 == -1 || 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][0] = s[rt] - 0; mndp[rt][0] = s[rt] - 0; return; } int ls = getPos(l, rt - 1); int rs = getPos(rt + 1, r); dfs(l, rt - 1, ls); dfs(rt + 1, r, rs); cnt[rt] = cnt[ls] + cnt[rs] + 1; if(P < M) { for(int i = 0; i <= cnt[ls]; i++) { for(int j = 0; j <= cnt[rs]; j++) { if(i + j > P) continue; if(P - i - j > 0) { chkmax(mxdp[rt][i + j + 1], mxdp[ls][i] + mxdp[rs][j]); chkmin(mndp[rt][i + j + 1], mndp[ls][i] + mndp[rs][j]); } if(M - (cnt[ls] - i) - (cnt[rs] - j) > 0) { 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 = 0; i <= cnt[ls]; i++) { for(int j = 0; j <= cnt[rs]; j++) { if(i + j > M) continue; if(M - i - j > 0) { chkmax(mxdp[rt][i + j + 1], mxdp[ls][i] - mndp[rs][j]); chkmin(mndp[rt][i + j + 1], mndp[ls][i] - mxdp[rs][j]); } if(P - (cnt[ls] - i) - (cnt[rs] - j) > 0) { 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 + 1); n = strlen(s + 1); scanf("%d%d", &P, &M); for(int i = 1; i <= n; i++) for(int j = 0; j <= min(P, M); j++) mxdp[i][j] = -inf, mndp[i][j] = inf; int root = getPos(1, n); dfs(1, n, root); printf("%d\n", mxdp[root][min(P, M)]); return 0; } /* */

Codeforces 935E Fafa and Ancient Mathematics dp