样例过了,0pts 求调
查看原帖
样例过了,0pts 求调
406934
xingyu369楼主2024/11/11 20:07
#include<bits/stdc++.h>
using namespace std;
int n,m,t,root,op,x,y,c;
int tot,nxt[4000005],to[4000005],head[2000005];
int tr[2000005];
int val[2000005],deep[2000005],fa[2000005][30];
vector<pair<int,pair<int,int> > >q[2000005];
pair<int,int> ans[2000005];
void add(int a,int b){
	to[tot]=b;
	nxt[tot]=head[a];
	head[a]=tot++;
}
void change(int x,int k){
	for(;x<=n;x+=(x&-x))
		tr[x]+=k;
}
int ask(int x){
	int ans=0;
	for(;x;x-=(x&-x))
		ans+=tr[x];
	return ans;
}
void dfs(int u,int f){
	fa[u][0]=f;
	for(int i=1;i<30;i++)
		fa[u][i]=fa[fa[u][i-1]][i-1];
	deep[u]=deep[f]+1;
	for(int i=head[u];~i;i=nxt[i]){
		int v=to[i];
		if(v==f)
			continue;
		dfs(v,u);
	}
}
int lca(int x,int y){
	if(deep[x]<deep[y])
		swap(x,y);
	if(x==y)
		return x;
	for(int i=0;i<=30;i++){
		if((deep[x]-deep[y])&(1<<i)){
			x=fa[x][i];
		}
	}
	if(x==y)
		return x;
	for(int i=0;i<30;i++){
		if(fa[x][i]!=fa[y][i]){
			x=fa[x][i];
			y=fa[y][i];
		}
	}
	if(x==y)
		return x;
	return fa[x][0];
}
void ddfs(int u,int f){
	if(val[u])
		change(val[u]+1,1);
	for(int i=0;i<q[u].size();i++){
//		if(q[u][i].second.first==1)
//			cout<<"**"<<u<<"*"<<q[u][i].first<<"*"<<ask(q[u][i].first)<<"**\n";
		ans[q[u][i].second.first].second+=q[u][i].second.second*(ask(q[u][i].first));
	}
	for(int i=head[u];~i;i=nxt[i]){
		int v=to[i];
		if(v==f)
			continue;
		ddfs(v,u);
	}
	if(val[u])
		change(val[u]+1,-1);
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	memset(head,-1,sizeof head);
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>t;
		if(t==0)
			root=i;
		else{
			add(i,t);
			add(t,i);
		}
	}
	dfs(root,0);
	cin>>m;
	for(int i=1;i<=m;i++){
		cin>>op;
		if(op==1){
			cin>>x>>y>>c;
			q[x].push_back({max(i-c+1,1),{i,1}});
			q[y].push_back({max(i-c+1,1),{i,1}});
			q[lca(x,y)].push_back({max(i-c+1,1),{i,-2}});
			ans[i].first=deep[x]+deep[y]-2*deep[lca(x,y)]+1;
		}else{
			cin>>t;
			val[t]=i;
		}
	}
	ddfs(root,0);
	for(int i=1;i<=m;i++){
		if(ans[i].first)
			cout<<ans[i].first<<' '<<ans[i].second<<'\n';
	}
	return 0;
}
//7
//0 1 2 3 3 2 1
2024/11/11 20:07
加载中...