Submission #545694

#TimeUsernameProblemLanguageResultExecution timeMemory
545694shark25361Ball Machine (BOI13_ballmachine)C++14
100 / 100
472 ms61748 KiB
#include<bits/stdc++.h>
#include <iomanip>
using namespace std;

#define FIO ios_base::sync_with_stdio(false);cin.tie(0);
#define ll long long
#define for_t ll T;cin>>T;while(T--)
#define endl "\n"
#define mod 1000000007
#define inf 1000000000000000001
#define all(c) c.begin(),c.end()
#define pb push_back
#define lc(curr) (curr * 2)
#define rc(curr) ((curr * 2) + 1)

const int maxn = 100005;

vector<ll> adj[maxn];
ll parent[maxn];
vector<bool> hasball(maxn,false);
ll cnt,root,last;
ll minnode[maxn];//min node in the subtree of i
vector<ll> order;
map<ll,ll> mp;
set<pair<ll,ll>> nb;//these nodes do not have balls
ll tin[maxn];
ll tout[maxn];
ll timer = 0;
ll up[maxn][35];

//find the contiguous nodes in ancestors of i that have a ball
void remnode(ll i)
{
    ll cnt = 0;
    ll curr = i;
    for(int j = 30;j >= 0;j--)
    {
        if(hasball[up[curr][j]])
        {
            curr = up[curr][j];
            cnt += pow(2,j);
        }
    }
    hasball[curr] = false;
    nb.insert({mp[curr],curr});
    cout << cnt << endl;
}

bool comp(ll i,ll j)
{
    return minnode[i] < minnode[j];
}

void dfs(ll i)
{
    minnode[i] = i;
    for(auto it:adj[i])
    {
        dfs(it);
        minnode[i] = min(minnode[i],minnode[it]);
    }
}

void dfs2(ll i)
{
    for(auto it:adj[i])
    {
        dfs2(it);
        order.pb(it);
    }
    order.pb(i);
    mp[i] = order.size() - 1;
    nb.insert({mp[i],i});
}

void lcadfs(ll i,ll parent)
{
    tin[i] = timer++;
    up[i][0] = parent;
    for(int j = 1;j <= 30;j++)
    {
        up[i][j] = up[up[i][j - 1]][j - 1];
    }
    for(auto it:adj[i])
    {
        lcadfs(it,i);
    }
    tout[i] = timer++;
}

void sol()
{
    ll n,q;
    cin >> n >> q;
    for(int i = 1;i <= n;i++)
    {
        cin >> parent[i];
        if(parent[i] == 0)
        {
            root = i;
        }
        else
        {
            adj[parent[i]].pb(i);
        }
    }
    dfs(root);
    for(int i = 1;i <= n;i++)
    {
        sort(all(adj[i]),comp);
    }
    dfs2(root);
    memset(up,0,sizeof(up));
    lcadfs(root,0);
    for(int i = 0;i < q;i++)
    {
        ll x,y;
        cin >> x >> y;
        if(x == 1)
        {
            for(int j = 0;j < y;j++)
            {
                ll u = (*nb.begin()).second;
                hasball[u] = true;
                last = u;
                nb.erase(*nb.begin());
            }
            cout << last << endl;
        }
        else
        {
            remnode(y);
        }
    }
}

int main()
{
    FIO
    sol();
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...