一般这种要倒着来。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define PII pair<int, int> #define y1 skldjfskldjg #define y2 skldfjsklejg using namespace std; const int N = 1e5 + 7; const int M = 1e7 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 998244353; int n, m, cur, x, up, a[N], f[20][1 << 20], op[20], cnt[1 << 20]; char t[20][3]; int dp(int x, int s) { if(s == up - 1) return 0; if(f[x][s] != inf) return f[x][s]; f[x][s] = op[x] == 1 ? -inf : inf; for(int j = 0; j < n; j++) { if((s >> j) & 1) continue; int add = t[x][0] == 'p' ? a[j] : 0; if(op[x] == 1) f[x][s] = max(f[x][s], dp(x + 1, s | (1 << j)) + add); else f[x][s] = min(f[x][s], dp(x + 1, s | (1 << j)) - add); } return f[x][s]; } int main() { memset(f, inf, sizeof(f)); scanf("%d", &n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); sort(a, a + n); reverse(a, a + n); scanf("%d", &m); n = min(n, m); up = 1 << n; for(int i = 0; i < m; i++) scanf("%s%d", t[i], &op[i]); printf("%d\n", dp(0, 0)); return 0; } /* */