CF570D Tree Requests(dsu on tree)

题解:
dsu on tree
首先dsu on tree是一个离线的算法,所以我们需要先把他们的询问储存起来,然后进行操作。

针对于每一个结点,我们先统计出他和他子树的所有信息,然后对于这个结点来说,我们已经把对于这个结点要查询的信息统计下来了,我们去暴力查询一下这个结点下深度每个字母的个数即可,对于出现次数为奇数的字母,我们最多可以允许有一个这样的字母(回文串放在中间)。最后输出即可。

代码:

/*Keep on going Never give up*/
//#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
//#define int long long

#define endl '\n'
#define Accepted 0
#define AK main()
#define I_can signed
using namespace std;
const int maxn =5e5+10;
const int MaxN = 0x3f3f3f3f;
const int MinN = 0xc0c0c00c;
typedef long long ll;
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;

vector<int> edge[maxn];
int dep[maxn];
int sz[maxn],son[maxn];
vector<pair<int,int> > v[maxn];
int ans[maxn],a[maxn];
string s;
void dfs(int x,int fa){
    sz[x]=1;
    dep[x]=dep[fa]+1;
    for(auto i:edge[x]){
        if(i==fa) continue;
        dfs(i,x);
        sz[x]+=sz[i];
        if(sz[i]>sz[son[x]]) son[x]=i;
    }
}

int flag;
int cnt[maxn][30];
void cal(int x,int val){
    cnt[dep[x]][a[x]]+=val;
    for(auto i:edge[x]){
        if(i==flag) continue;
        cal(i,val);
    }
}


void dsu(int x,int keep){
    for(auto i:edge[x]){
        if(i==son[x]) continue;
        dsu(i,false);
    }
    if(son[x]){
        dsu(son[x],true);
        flag=son[x];
    }
    cal(x,1);
    for(auto i:v[x]){
        int temp=0;
        for(int j=1;j<=26;j++){
            if(cnt[i.first][j]&1) temp++;
        }
        if(temp>=2){
            ans[i.second]=0;
        }
        else ans[i.second]=1;
    }
    if(son[x]){
        flag=0;
    }
    if(!keep) cal(x,-1);

}


int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int n,m;
    cin>>n>>m;
    for(int i=2;i<=n;i++){
        int x;
        cin>>x;
        edge[x].push_back(i);
    }
    cin>>s;
    for(int i=0;i<s.size();i++){
        a[i+1]=s[i]-'a'+1;
    }
    dfs(1,0);

    for(int i=1;i<=m;i++){
        int x,y;
        cin>>x>>y;
        v[x].push_back({y,i});
    }
    dsu(1,0);
    for(int i=1;i<=m;i++){
        if(ans[i]) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值