codeforces 570 D. Tree Requests (dfs序)

因为字母的排列顺序是任意的,所以判断能否形成回文串的条件就成了出现次数为奇数的字母的个数是否大于1个,如果是,那么一定不能形成回文串,否则一定可以.

为了找到以节点v为根的 subtree 中深度为h的后代,需要求出dfs序列,并且记录每个节点初次访问的时间戳和离开它的时间戳,然后二分.

貌似也可以用树状数组做?

 1/*************************************************************************
 2	> File Name: code/cf/#316/D.cpp
 3	> Author: 111qqz
 4	> Email: rkz2013@126.com 
 5	> Created Time: 2015年08月15日 星期六 02时55分55秒
 6 ************************************************************************/
 7#include <bits/stdc++.h>
 8
 9
10using namespace std;
11const int N=5E5+7;
12int n,m;
13vector<int> adj[N];
14char S[N];
15vector<int> occ[N][26];
16int in[N], out[N], now;
17
18void dfs(int u, int depth)
19{
20    occ[depth][S[u]-'a'].push_back(++now);
21    in[u]=now;
22    vector<int>::iterator it;
23    for (it=adj[u].begin();it!=adj[u].end();it++)
24    {
25	dfs(*it,depth+1);
26    }
27    out[u]=now;
28}
29
30int main()
31{
32    scanf("%d %d",&n,&m);
33    for(int i=2; i<=n; i++)
34    {
35        int a;
36        scanf("%d",&a);
37        adj[a].push_back(i);
38    }
39    scanf("%s", S+1);
40    dfs(1, 1);
41    while(m--)
42    {
43        int v, h;
44        scanf("%d %d",&v,&h);
45        int odd=0;
46        for(int i=0; i<26; i++)
47        {
48            int cnt=upper_bound(occ[h][i].begin(), occ[h][i].end(), out[v])-
49                    lower_bound(occ[h][i].begin(), occ[h][i].end(), in[v]);
50            if(cnt%2==1)
51            {
52                odd++;
53                if(odd>1)
54                    break;
55            }
56        }
57        if(odd>1)
58            printf("No\n");
59        else
60            printf("Yes\n");
61    }
62    return 0;
63}