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;
#define int long long
#define F first
#define S second
#define pii pair<int, int>
#define pb push_back
#define pp pop_back
#define all(x) x.begin(), x.end()
const int N = 1e5 + 12, M = 20, SQ = 400;
vector<int> g[N];
int n, q, t, f[N], p[N], par[M][N], root, d[N], h[N], sum[SQ];
bool dp[SQ], a[SQ * SQ + 12];
void ip() {
cin >> n >> q;
for (int i = 0; i < n; i++) {
int u;
cin >> u;
u--;
par[0][i] = u;
if (u == -1)
root = i;
else {
g[u].pb(i);
g[i].pb(u);
}
}
par[0][root] = root;
}
void dfs1(int u) {
d[u] = u;
for (auto i: g[u])
if (i != par[0][u]) {
h[i] = h[u] + 1;
dfs1(i);
d[u] = min(d[u], d[i]);
}
}
void dfs2(int u) {
vector<pii> tmp;
for (auto i: g[u])
if (i != par[0][u])
tmp.pb({d[i], i});
sort(all(tmp));
for (auto i: tmp)
dfs2(i.S);
f[t] = u;
p[u] = t;
t++;
}
void pre() {
dfs1(root);
dfs2(root);
for (int i = 1; i < M; i++)
for (int j = 0; j < n; j++)
par[i][j] = par[i - 1][par[i - 1][j]];
}
void add(int x) {
for (int i = 0; (i + 1) * SQ - 1 < x; i++) {
sum[i] = SQ;
dp[i] = true;
}
if (!dp[x / SQ])
for (int i = (x / SQ) * SQ; i <= x; i++)
if (!a[i]) {
a[i] = true;
sum[x / SQ]++;
}
}
void rem(int x) {
if (dp[x / SQ]) {
fill(a + x - x % SQ, a + x - x % SQ + SQ, 1);
sum[x / SQ] = SQ - 1;
dp[x / SQ] = false;
a[x] = false;
}
else if (a[x]) {
a[x] = false;
sum[x / SQ]--;
}
}
int ask(int x) {
int res = 0;
for (int i = 0; (i + 1) * SQ - 1 < x; i++)
res += sum[i];
if (dp[x / SQ])
res += (x % SQ) + 1;
else
for (int i = x - x % SQ; i <= x; i++)
res += a[i];
return res;
}
void query() {
while (q--) {
int u, v;
cin >> u >> v;
if (u == 1) {
int l = -1, r = n;
while (r - l > 1) {
int mid = (l + r) / 2;
if (mid + 1 - ask(mid + 1) <= v)
l = mid;
else
r = mid;
}
cout << f[l] + 1 << '\n';
add(l);
}
else {
v--;
int z = v;
for (int i = M - 1; ~i; i--)
if ((ask(p[par[i][v]]) - ask(p[par[i][v]] - 1)) > 0)
v = par[i][v];
cout << h[z] - h[v] << '\n';
rem(p[v]);
}
}
}
int32_t main() {
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
ip(), pre(), query();
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... |