鏈接
https://codeforces.com/contest/570/problem/D
題解
對於每個深度統計每種字符的數目,如果數目爲奇數的字符不多於種就能構成迴文
代碼
#include <bits/stdc++.h>
#define maxn 500010
#define maxe 1000010
using namespace std;
struct Graph
{
int etot, head[maxn], to[maxe], next[maxe], w[maxe];
void clear(int N)
{
for(int i=1;i<=N;i++)head[i]=0;
etot=0;
}
void adde(int a, int b, int c){to[++etot]=b;w[etot]=c;next[etot]=head[a];head[a]=etot;}
}G;
struct ShuLianPouFen
{
int size[maxn], top[maxn], tid[maxn], tim, untid[maxn], deep[maxn], son[maxn], fa[maxn];
void dfs1(Graph &G, int pos)
{
int p, v;
size[pos]=1;
for(p=G.head[pos];p;p=G.next[p])
{
if((v=G.to[p])==fa[pos])continue;
fa[v]=pos;
deep[v]=deep[pos]+1;
dfs1(G,v);
if(size[v]>size[son[pos]])son[pos]=v;
size[pos]+=size[v];
}
}
void dfs2(Graph &G, int pos, int tp)
{
int p, v;
top[pos]=tp;
tid[pos]=++tim;
untid[tid[pos]]=pos;
if(son[pos])dfs2(G,son[pos],tp);
for(p=G.head[pos];p;p=G.next[p])
if((v=G.to[p])!=fa[pos] and v!=son[pos])dfs2(G,v,v);
}
void run(Graph &G, int root)
{
tim=0;
deep[root]=1;
dfs1(G,root);
dfs2(G,root,root);
}
}SP;
int ans[maxn], N, M, h[maxn], cnt[maxn][30], c[maxn], forb;
char s[maxn];
vector<int> qlis[maxn];
void force(int pos, int pre, int opt)
{
cnt[SP.deep[pos]][c[pos]]+=opt;
for(auto p=G.head[pos];p;p=G.next[p])
if(G.to[p]!=pre and G.to[p]!=forb)
force(G.to[p],pos,opt);
}
void dfs(int pos, int pre, int H)
{
for(auto p=G.head[pos];p;p=G.next[p])
if(G.to[p]!=pre and G.to[p]!=SP.son[pos])
dfs(G.to[p],pos,0);
if(SP.son[pos])dfs(SP.son[pos],pos,1);
forb=SP.son[pos];
force(pos,pre,+1);
for(auto q:qlis[pos])
{
int x=0;
for(int i=1;i<=26;i++)x+=(cnt[h[q]][i])&1;
if(x<=1)ans[q]=true;
}
forb=0;
if(H==0)force(pos,pre,-1);
}
int main()
{
int i, j, p;
ios::sync_with_stdio(false);
cin>>N>>M;
for(i=2;i<=N;i++)
{
cin>>p;
G.adde(p,i,0);
G.adde(i,p,0);
}
SP.run(G,1);
cin>>s+1;
for(i=1;i<=N;i++)c[i]=s[i]-'a'+1;
for(i=1;i<=M;i++)
{
int v;
cin>>v>>h[i];
qlis[v].emplace_back(i);
}
dfs(1,0,0);
for(i=1;i<=M;i++)
if(ans[i])cout<<"Yes\n";
else cout<<"No\n";
return 0;
}