This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 1e6 + 10;
const int LOG = 22;
const int INF = 0x3f3f3f3f;
int n, q, filled[MAX], root, t, order[MAX], dp[MAX][LOG], d[MAX], mn[MAX];
vector<int> adj[MAX];
set<pair<int, int>> s;
bool cmp(int u, int v){ return mn[u] < mn[v]; }
void dfs(int u, int p, int dist){
d[u] = dist, mn[u] = u;
for(auto v : adj[u]){
if(v == p) continue;
dfs(v, u, dist + 1);
mn[u] = min(mn[u], mn[v]);
}
sort(adj[u].begin(), adj[u].end(), cmp);
}
void dfs2(int u, int p){
for(auto v : adj[u]){
if(v == p) continue;
dfs2(v, u);
}
order[u] = ++t;
s.insert({order[u], u});
}
int query(ll u){
int old = d[u];
for(int i = LOG - 1; i >= 0; i--){
int j = dp[u][i];
if(j == -1) continue;
if(filled[j]) u = j;
}
s.insert({order[u], u});
filled[u] = false;
return old - d[u];
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> q;
memset(dp, -1, sizeof(dp));
for(int i = 1; i <= n; i++){
int x; cin >> x;
if(x != 0){
adj[x].push_back(i);
adj[i].push_back(x);
dp[i][0] = x;
}else{ root = i; }
}
dfs(root, -1, 0);
dfs2(root, -1);
for(int j = 1; j < LOG; j++){
for(int i = 1; i <= n; i++){
if(dp[i][j - 1] == -1) continue;
dp[i][j] = dp[dp[i][j - 1]][j - 1];
}
}
while(q--){
int op, k; cin >> op >> k;
if(op == 1){
int last = -1;
while(k-- && s.size()){
int cur = (*(s.begin())).second;
filled[cur] = true;
last = cur;
s.erase(s.begin());
}
cout << last << '\n';
}else{
cout << query(k) << '\n';
}
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |