tle 树连剖分求调
查看原帖
tle 树连剖分求调
744895
liaoxingrui楼主2024/12/3 17:03
#include<bits/stdc++.h>
#define mid (l+r>>1)
using namespace std;
const int N=1e4+5;
int t,n,x,y,val,cnt,tot;
int fa[N],dep[N],siz[N],son[N],top[N],rnk[N],tmp[N],head[N],tree[N<<2];
string opt;
vector<int> a[N];
struct node{
	int x,y,val;
}nex[N<<1];
void add(int x,int y,int val){
	tot++;
	nex[tot].x=y;
	nex[tot].y=head[x];
	nex[tot].val=val;
	head[x]=tot;
}
void dfs1(int node){
	siz[node]=1;
	for(int i=head[node];i;i=nex[i].y){
		int w=nex[i].x;
		if(w!=fa[node]){
			fa[w]=node;
			dep[w]=dep[node]+1;
			dfs1(w);
			siz[node]+=siz[w];
			if(siz[w]>siz[son[node]])
				son[node]=w; 
		}
		else
			tmp[node]=nex[i].val;
	} 
} 
void dfs2(int node,int x){
	top[node]=x;
	a[x].push_back(node);
	cnt++;
	rnk[node]=cnt;
	if(!son[node])
		return;
	dfs2(son[node],x);
	for(int i=head[node];i;i=nex[i].y){
		int w=nex[i].x;
		if(w!=fa[node]&&w!=son[node])
			dfs2(w,w);
	}
}
int Lca(int x,int y){
	while(top[x]!=top[y]){
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		x=fa[top[x]];
	}
	return dep[x]<dep[y]?x:y;
}
void pushup(int node){
	tree[node]=tree[node<<1]+tree[node<<1|1];
}
void build(int node,int l,int r){
	if(l==r){
		tree[node]=tmp[rnk[l]];
		return; 
	}
	build(node<<1,l,mid);
	build(node<<1|1,mid+1,r);
	pushup(node); 
}
int query(int node,int l,int r,int x,int y){
	if(x<=l&&r<=y)
		return tree[node];
	int sum=0;
	if(x<=mid)
		sum+=query(node<<1,l,mid,x,y);
	if(mid<y)
		sum+=query(node<<1|1,mid+1,r,x,y);
	return sum;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>t;
	while(t--){
		tot=0;
		cnt=0;
		memset(siz,0,sizeof siz);
		memset(nex,0,sizeof nex);
		cin>>n;
		for(int i=1;i<n;i++){
			cin>>x>>y>>val;
			add(x,y,val);
			add(y,x,val);
		}
		dfs1(1);
 		dfs2(1,1);
		build(1,1,n); 
		while(cin>>opt&&opt!="DONE"){
			cin>>x>>y;
			if(opt=="DIST"){
				int ans=0;
				while(top[x]!=top[y]){
					if(dep[top[x]]<dep[top[y]])
						swap(x,y);
					ans+=query(1,1,n,rnk[top[x]],rnk[x]);
					x=fa[top[x]];
				}
				if(dep[x]>dep[y])
					swap(x,y);
				cout<<ans+query(1,1,n,rnk[x]+1,rnk[y])<<endl;
			}
			else{
				cin>>val;
				int lca=Lca(x,y);
				if(dep[x]-dep[lca]+1<val){
					val=dep[x]+dep[y]-(dep[lca]<<1)+2-val;
					swap(x,y);
				}
				if(dep[x]<dep[y]&&x==lca){
					val=dep[y]-dep[x]+2-val;
					swap(x,y);
				}
				while(val>dep[x]-dep[top[x]]+1){
					val-=dep[x]-dep[top[x]]+1;
					x=fa[top[x]];
				}
				if(x==top[x])
					cout<<a[top[x]][val-1]<<endl;
				else
					cout<<a[top[x]][a[top[x]].size()-val]<<endl;
			}
		}
		for(int i=1;i<=n;i++)
			a[i].clear();
	}
	return 0;
}
2024/12/3 17:03
加载中...