Submission #643405

#TimeUsernameProblemLanguageResultExecution timeMemory
643405GaLzBall Machine (BOI13_ballmachine)C++14
25 / 100
52 ms13968 KiB
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vll;
const ll mod=1e9+7;
const ll maxn=1e5+5;
const ll INF=1e18;
#define ok ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define fi first
#define se second
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define endl '\n'
int n, q, t, x, mn[maxn], par[maxn], root, dis[maxn], hrs, cnt, ans, nmr[maxn];
vi adj[maxn], arr;
bool use[maxn];
bool sub1=1;
priority_queue<pii, vector<pii>, greater<>> pq;
void dfs(int now) {
    mn[now]=now;
    for(auto it : adj[now]) {
        dis[it]=dis[now]+1;
        dfs(it);
        mn[now]=min(mn[now], mn[it]);
    }
}
void dfs2(int now) {
    if(!adj[now].empty()) {
        if(mn[adj[now][0]]>mn[adj[now][1]]) {
            dfs2(adj[now][1]);
            dfs2(adj[now][0]);
        } else {
            dfs2(adj[now][0]);
            dfs2(adj[now][1]);
        }
    }
    arr.pb(now);
}
int main() {
    ok
    cin >> n >> q;
    for(int i=1; i<=n; i++) {
        cin >> par[i];
        if(par[i]==0){
            root=i;
        } else adj[par[i]].pb(i);
    }
    dfs(root);
    for(int i=1; i<=n; i++) {
        if(!(adj[i].size()==2 || adj[i].empty())) sub1=0;
        if(adj[i].empty() && hrs && dis[i]!=hrs) sub1=0;
        if(adj[i].empty() && !hrs) hrs=dis[i];
    }
    if(sub1) {
        dfs2(root);
        for(auto it : arr) {
            cnt++;
            nmr[it]=cnt;
            pq.push({cnt, it});
        }
        while(q--) {
            cin >> t >> x;
            if(t==1) {
                while(x--) {
                    ans=pq.top().se;
                    use[pq.top().se]=1;
                    pq.pop();
                }
                cout << ans << endl;
            } else {
                ans=0;
                while(use[par[x]]) {
                    ans++;
                    x=par[x];
                }
                use[x]=0;
                pq.push({nmr[x], x});
                cout << ans << endl;
            }
        }
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...