树链剖分本机可过RE求助
查看原帖
树链剖分本机可过RE求助
749738
GJY2333楼主2023/10/12 18:02

RT

#include<stdio.h>
#include<string.h>
int head[100050],dep[50050],hson[50050],dfn[50050],fa[200200],siz[50050],top[50050];
int w[50050],a[50050];
int U[50050],V[50050];
int n;
struct node{
	int nxt,to,w;
}e[100050];

struct Tree{
	int maxn,l,r;
}t[200040];

int max(int a,int b) {
	if(a >= b) return a;
	return b;
}

void pushup(int p) {
	t[p].maxn=max(t[p<<1].maxn,t[p<<1|1].maxn);
}

void Build(int l,int r,int p) {
	t[p].l=l;t[p].r=r;
	if(l == r) {
		t[p].maxn=a[l]; return ;
	}
	int mid=l+r>>1;
	Build(l,mid,p<<1); Build(mid+1,r,p<<1|1);
	pushup(p);
}

void Modify(int l,int r,int p,int w) {
	if(l <= t[p].l && r >= t[p].r) {
		t[p].maxn=w;
		return ;
	}
	if(l <= t[p<<1].r) Modify(l,r,p<<1,w);
	if(r >= t[p<<1|1].l) Modify(l,r,p<<1|1,w);
	pushup(p);
}

int Query(int l,int r,int p) {
	if(l <= t[p].l && r >= t[p].r) {
		return t[p].maxn;
	}
	int ans=-1145141919;
	if(l <= t[p<<1].r) ans=max(ans,Query(l,r,p<<1));
	if(r >= t[p<<1|1].l) ans=max(ans, Query(l,r,p<<1|1));
	return ans;
}

int tot;
void add(int u,int v,int w) {
	e[++tot].to=v;
	e[tot].w=w;
	e[tot].nxt=head[u];
	head[u]=tot;
}

int cnt;
void dfs1(int u,int f) {
	dep[u]=dep[f]+1; fa[u]=f; siz[u]=1;
	for(int i=head[u];i;i=e[i].nxt) {
		int to=e[i].to;
		if(to == f) continue;
		w[to]=e[i].w;
		dfs1(to,u);
		siz[u]+=siz[to];
		if(siz[to] > siz[hson[u]]) hson[u]=to;
	}
}

void dfs2(int u,int t) {
	top[u]=t; dfn[u]=++cnt; a[cnt]=w[u];
	if(!hson[u]) return ;
	dfs2(hson[u],t);
	for(int i=head[u];i;i=e[i].nxt) {
		int to=e[i].to;
		if(to == fa[u] || to == hson[u]) continue;
		dfs2(to,to);
	}
}

int Get(int x,int y) {
	int ans=-2e9;
	while(top[x] != top[y]) {
		if(dep[top[x]] < dep[top[y]]) {
			int c=x; x=y; y=c;
		}
		ans=max(ans,Query(dfn[top[x]],dfn[x],1));
		
		x=fa[top[x]];
	}
	if(x == y) return ans;
	if(dep[x] > dep[y]) {
		int c=x; x=y;y=c;
	}
	ans=max(ans,Query(dfn[x]+1,dfn[y],1));
	return ans;
}
char s[50];

void clear() {
	memset(head,0,sizeof(head));
	tot=0;
	cnt=0;
}

int main() {
	int t; scanf("%d", &t);
	while(t --) {
		scanf("%d", &n);
		clear();
		for(int i=1;i<n;i++) {
			int u,v,w; scanf("%d%d%d", &u, &v, &w);
			add(u,v,w); add(v,u,w);
			U[i]=u; V[i]=v;
		}
		dfs1(1,0); 
		dfs2(1,1); Build(1,n,1);
		
		while(1) {
			scanf("%s",s);
			if(s[0] == 'D') break;
			if(s[0] == 'C') {
				int x,t; scanf("%d%d", &x, &t);
				int u=U[x],v=V[x];
				if(fa[u] == v) {
					int c=u; u=v; v=c;
				}
				Modify(dfn[v],dfn[v],1,t);
			}
			else {
				int a,b;scanf("%d%d", &a, &b);
				printf("%d\n", Get(a,b));
			}
		}		
	}
	return 0;
}
/*
1
3
1 2 1
2 3 2
QUERY 1 2
CHANGE 1 3
QUERY 1 2
DONE
*/
2023/10/12 18:02
加载中...