感觉这个思路相当巧妙啊。。
考虑最普通的 dp[ i ] = max(dp[ j ] + w[ i ] opt w[ j ]), j 是 i 的祖先。
把(2 << 16) 分成前八位和后八位去优化最朴素的dp。 修改遍历后八位, 查询遍历前八位。
#pragma GCC optimize(2) #pragma GCC optimize(3) #include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned 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 ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = (1 << 16) + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = (int)1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} int n, w[N], c[1 << 8]; LL dp[N], f[1 << 8][1 << 8], g[N][1 << 8]; char op[10]; vector<int> G[N]; inline LL calc(int a, int b) { if(*op == ‘A‘) return a & b; else if(*op == ‘O‘) return a | b; else return a ^ b; } void dfs(int u) { dp[u] = 0; int now_a = w[u] >> 8; int now_b = w[u] & 255; for(int pre_a = 0; pre_a < 256; pre_a++) { if(c[pre_a]) { chkmax(dp[u], f[pre_a][now_b] + ((calc(now_a, pre_a)) << 8)); } } for(int pre_b = 0; pre_b < 256; pre_b++) { g[u][pre_b] = f[now_a][pre_b]; } c[now_a]++; for(int pre_b = 0; pre_b < 256; pre_b++) { chkmax(f[now_a][pre_b], dp[u] + calc(now_b, pre_b)); } for(auto &v : G[u]) { dfs(v); } c[now_a]--; for(int pre_b = 0; pre_b < 256; pre_b++) { f[now_a][pre_b] = g[u][pre_b]; } } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%s", &n, op); for(int i = 1; i <= n; i++) { G[i].clear(); } for(int i = 1; i <= n; i++) { scanf("%d", &w[i]); } for(int i = 2; i <= n; i++) { int pa; scanf("%d", &pa); G[pa].push_back(i); } dfs(1); int ans = 0; for(int i = 1; i <= n; i++) { add(ans, 1LL * i * (dp[i] + w[i]) % mod); } printf("%d\n", ans); } return 0; } /* */
原文地址:https://www.cnblogs.com/CJLHY/p/11517001.html
时间: 2024-11-14 18:59:03