This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
// Success consists of going from failure to failure without loss of enthusiasm
#include <bits/stdc++.h>
using namespace std;
#define nl '\n'
#define pb push_back
#define pf push_front
#define mp make_pair
#define f first
#define s second
#define sz(x) int(x.size())
template<class T> using V = vector<T>;
using pi = pair<int, int>;
using vi = V<int>;
using vpi = V<pi>;
using ll = long long;
using pl = pair<ll, ll>;
using vpl = V<pl>;
using vl = V<ll>;
using db = long double;
template<class T> using pq = priority_queue<T, V<T>, greater<T>>;
const int MOD = 1e9 + 7;
const ll INFL = ll(1e17);
const int LG = 18;
int main() {
cin.tie(0)->sync_with_stdio(0);
int N, Q; cin >> N >> Q;
int R = -1;
vi P(N);
V<vi> chd(N); for(int i = 0; i < N; i++) {
int p; cin >> p; --p;
if (p != -1) chd[p].pb(i), P[i] = p;
else R = i, P[i] = -1;
}
vi mn(N, MOD), dep(N);
V<vi> up(N+1, vi(LG, N));
function<void(int)> gen = [&](int u) {
for(int i = 1; i < LG; i++) up[u][i] = up[up[u][i-1]][i-1];
mn[u] = u;
for(auto& v : chd[u]) {
up[v][0] = u; dep[v] = dep[u] + 1; gen(v);
mn[u] = min(mn[v], mn[u]);
}
};
dep[R] = 0; gen(R);
vi deg(N); for(int i = 0; i < N; i++) deg[i] = sz(chd[i]);
vi ord(N); int cur = 0;
function<void(int)> dfs = [&](int u) {
sort(begin(chd[u]), end(chd[u]), [&](int x, int y) {
return mn[x] < mn[y];
});
for(auto v : chd[u]) dfs(v);
ord[u] = cur++;
};
dfs(R);
pq<pi> W; for(int i = 0; i < N; i++) W.push(mp(ord[i], i));
vi C(N+1); // C[i] = 0 (off) / 1 (on)
for(int t = 0; t < Q; t++) {
int type; cin >> type;
if (type == 1) {
int k; cin >> k;
int lst = -1;
while(k--) {
int u = W.top().s; W.pop();
// cout << "ADD: " << u << endl;
C[u] = 1; lst = u;
}
cout << lst + 1 << nl;
} else {
int u; cin >> u; --u;
int d = dep[u];
assert(C[u] == 1);
for(int i = LG-1; i >= 0; i--) {
// cout << u << " " << i << endl;
// cout << up[u][i] << endl;
if (C[up[u][i]]) u = up[u][i];
}
// cout << "REM: " << u << endl;
C[u] = 0; if (u != N) W.push(mp(ord[u], u));
cout << d - dep[u] << nl;
}
}
// for(int i = 0; i < N; i++) cout << i << " " << C[i] << endl;
exit(0-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... |