feat: 添加P5658题解实现括号匹配与树遍历算法

实现基于深度优先搜索的括号匹配算法,计算树结构中每个节点的权值并求异或和。主要功能包括:
- 处理输入树结构和括号序列
- 使用栈进行括号匹配
- 动态规划计算节点权值
- 最终结果异或运算
This commit is contained in:
Zengtudor 2025-09-27 19:14:00 +08:00
parent 25605159cc
commit 0cea6a732c

55
src/9/27/P5658.cpp Normal file
View File

@ -0,0 +1,55 @@
#include <cstdint>
#include <deque>
#include <iostream>
#include <istream>
#include <vector>
using ll = int64_t;
const ll maxn = 5e5+5;
ll n,ans,dp[maxn],f[maxn],k[maxn];
char c[maxn];
std::vector<std::vector<ll>> s;
std::vector<ll> stk;
static inline void dfs(ll u){
ll pos =0;
bool ispushed = false;
if(c[u]=='('){
stk.push_back(u);
ispushed=true;
}else if(stk.size()){
pos = stk.back();
stk.pop_back();
dp[u]=dp[f[pos]]+1;
}
k[u]=k[f[u]]+dp[u];
ans^=u*k[u];
for(ll v:s[u]){
dfs(v);
}
if(ispushed){
stk.pop_back();
}
if(pos){
stk.push_back(pos);
}
}
int main(){
std::iostream::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin>>n;
s.resize(n+1);
for(ll i=1;i<=n;i++){
std::cin>>c[i];
}
for(ll i=2;i<=n;i++){
ll tmp;
std::cin>>tmp;
s[tmp].push_back(i);
f[i]=tmp;
}
dfs(1);
std::cout<<ans<<'\n';
}