跳到正文

个人记录

[ICPC 2017 Urumqi R] A Possible Tree

Big_Cake_awa约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月17日
收录
2026年8月17日
更新
2026年8月17日
篇幅
约 3 分钟

版本

  1. v1当前

只会做树上题的神人。

下面设 vv 为 uu 的儿子节点。

换根 DP。考虑从根从 u→vu\rightarrow v 哪些点对的 LCA 会改变。

显然当 LCA 恰好为 uu,且两点之间横跨了 u−vu-v 这条边的点对会变为 vv。

那么考虑用树上差分记录每条边有多少点对覆盖。设 cvc_v 表示有 cvc_v 对点对经过 u−vu-v 这条边,fuf_u 表示 uu 为根的答案,那么:

fv=fu+cv⋅(v−u)f_v=f_u+c_v\cdot (v-u)

然后没了。时间复杂度 O((n+m)log⁡n)O((n+m)\log n)。

哦哦记得开 long long。

AC code
C++
const int N=1e5+8;
int n,m;
struct edge {
	int v,nxt;
}G[N<<1];
int cnt,hd[N];
void add_edge(int u,int v) {
	G[++cnt].v=v;
	G[cnt].nxt=hd[u];
	hd[u]=cnt;
}
int ans[N];
int x[N],y[N];
int d[N];
int fat[N][28];
int dep[N];
void dfs(int u,int fa) {
	fat[u][0]=fa;
	dep[u]=dep[fa]+1;
	for(int i=hd[u];i;i=G[i].nxt) {
		int v=G[i].v;
		if(v==fa) continue;
		dfs(v,u);
	}
}
int LCA(int x,int y) {
	if(dep[x]<dep[y]) swap(x,y);
	req(j,20,0) if(dep[fat[x][j]]>=dep[y])
		x=fat[x][j];
	if(x==y) return x;
	req(j,20,0) if(fat[x][j]!=fat[y][j])
		x=fat[x][j],y=fat[y][j];
	return fat[x][0];
}
void tag(int u,int fa) {
	for(int i=hd[u];i;i=G[i].nxt) {
		int v=G[i].v;
		if(v==fa) continue;
		tag(v,u);
		d[u]+=d[v];
	}
}
void solve(int u,int fa) {
	for(int i=hd[u];i;i=G[i].nxt) {
		int v=G[i].v;
		if(v==fa) continue;
		ans[v]=ans[u]+d[v]*(v-u);
		solve(v,u);
	}
}
void init() {
	cnt=0;
	rep(i,1,n) {
		hd[i]=0;
		ans[i]=0;
		dep[i]=0;
		d[i]=0;
	} 
}
signed main()
{
	int T;read(T);
	while(T--) {
		init();
		read(n);read(m);
		rep(i,1,n-1) {
			int u,v;read(u);read(v);
			add_edge(u,v);
			add_edge(v,u);
		}
		rep(i,1,m) read(x[i]),read(y[i]);
		dfs(1,0);
		rep(j,1,20) rep(i,1,n) 
			fat[i][j]=fat[fat[i][j-1]][j-1];
		rep(i,1,m) {
			int lca=LCA(x[i],y[i]);
			ans[1]+=lca;
			d[lca]-=2;d[x[i]]++;
			d[y[i]]++;
		}
		tag(1,0);
		solve(1,0);
		rep(i,1,n) print(ans[i]),print(' ');
		print('\n');
	}
	return 0;
}
原文