dp求助
查看原帖
dp求助
800543
NirvanaCeleste楼主2024/10/12 11:12
#include <bits/stdc++.h>
using namespace std;
const int maxn = 500500;
#define ll long long
int n;
string s;
int nxt[maxn];
ll dp[maxn],f[maxn];
//nxt 是最近一个可消除的子串的左端点 如没有可消除的子串则为0 
//dp 为以i为结尾的字符串有多少可消除的"串" (r < l,满足[r,l]是可消除的)
//这与 i为结尾的字符串有多少可消除的子串不同 i为结尾的字符串有多少可消除的子串是dp的前缀和 
int to[maxn*2],head[maxn*2],enext[maxn*2];
ll ans;
int tot;
inline void add(int u,int v){
	to[++tot] = v;
	enext[tot] = head[u];
	head[u] = tot;	
	return;
}
void pre(){
	cin >> n >> s;
	s = " " + s;
	int u;
	for(int i=2;i<=n;i++) scanf("%lld",&f[i]),add(f[i],i);
	return;
}
void dfs(int x,int father,long long res){
	if(s[x] == ')'){
		int t = father;
		while(t > 0){
			if(s[t] == '(') break;
			t = nxt[t];
			if(t) t--;
		}
		nxt[x] = t;
		int head_t = f[t];
		if(t) dp[x] = dp[head_t] + 1;
		res += dp[x];
		ans = ans^(res * x); 
	}
	for(int i=head[x];i;i=enext[i]){
		int v = to[i];
		dfs(v,x,res);
	}
	return;
}
int main(){
//	freopen("P5658_1.in","r",stdin);
	pre();
	dfs(1,0,0);
	cout<<ans;
	return 0;
}
2024/10/12 11:12
加载中...