이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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], lca[maxn][17];
vi adj[maxn], arr;
bool use[maxn];
bool sub1=1;
priority_queue<pii, vector<pii>, greater<>> pq;
bool cmp(int a, int b) {
return mn[a]<mn[b];
}
void dfs(int now, int fr) {
mn[now]=now;
lca[now][0]=fr;
for(int i=1; i<17; i++) {
lca[now][i]=lca[lca[now][i-1]][i-1];
}
for(auto it : adj[now]) {
dis[it]=dis[now]+1;
dfs(it, now);
mn[now]=min(mn[now], mn[it]);
}
}
void dfs2(int now) {
if(!adj[now].empty()) {
sort(adj[now].begin(), adj[now].end(), cmp);
for(auto it : adj[now]) {
dfs2(it);
}
}
arr.pb(now);
}
int main() {
// Bismillah AC
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, 0);
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];
}
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]]) {
for(int i=16; i>=0; i--) {
if(use[lca[x][i]]) {
ans+=dis[x]-dis[lca[x][i]];
x=lca[x][i];
break;
}
}
}
use[x]=0;
pq.push({nmr[x], x});
cout << ans << endl;
}
}
}
# | 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... |