570D - Tree Requests - CodeForces Solution


binary search bitmasks constructive algorithms dfs and similar graphs trees *2200

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>


// author: aykhn

using namespace std;

typedef long long ll;

#define OPT ios_base::sync_with_stdio(0); \
            cin.tie(0); \
            cout.tie(0)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pss pair<long,long>
#define all(v) v.begin(), v.end()
#define mpr make_pair
#define pb push_back
#define ts to_string
#define fi first
#define se second
#define ins insert
#define inf 0x3F3F3F3F
#define infll 0x3F3F3F3F3F3F3F3FLL
#define bpc __builtin_popcount
#define print(v) for(int i = 0; i < v.size(); i++) cout << v[i] << " "; cout<<endl;

int n;
string s;
vector<int> adj[2000001];
vector<pii> d[2000001];
int p[2000001];
int key[2000101];
int e[2000001];
int tim;

void dfs(int a, int de)
{
    key[a] = ++tim;
    if (d[de].size() == 0) d[de].pb(mpr(key[a], (1 << (s[a - 1] - 'a'))));
    else d[de].pb(mpr(key[a], d[de].back().se ^ (1 << (s[a - 1] - 'a'))));

    for (int &v : adj[a]) dfs(v, de + 1);

    e[a] = ++tim;
}

int main()
{
    OPT;
    int m;
    cin >> n >> m;

    for (int i = 2; i <= n; i++)
    {
        cin >> p[i];
        adj[p[i]].pb(i);
    }
    cin >> s;
    
    dfs(1, 1);

    while (m--)
    {
        int v, h;
        cin >> v >> h;

        int x = lower_bound(all(d[h]), mpr(key[v], -1)) - d[h].begin();
        int y = lower_bound(all(d[h]), mpr(e[v], -1)) - d[h].begin() - 1;

        if (y < 0)
        {
            cout << "Yes" << endl;
            continue;
        }
        int val = 0;
        if (x > 0) val = d[h][y].se ^ d[h][x - 1].se;
        else val = d[h][y].se;
        cout << (bpc(val) <= 1 ? "Yes" : "No") << endl;
    }
}


Comments

Submit
0 Comments
More Questions

281A - Word Capitalization
1646A - Square Counting
266A - Stones on the Table
61A - Ultra-Fast Mathematician
148A - Insomnia cure
1650A - Deletions of Two Adjacent Letters
1512A - Spy Detected
282A - Bit++
69A - Young Physicist
1651A - Playoff
734A - Anton and Danik
1300B - Assigning to Classes
1647A - Madoka and Math Dad
710A - King Moves
1131A - Sea Battle
118A - String Task
236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets