跳到正文

题解

P4374题解

MeowScore约 5 分钟
原文
文章信息与版本

文章信息

发布
2021年12月10日
收录
2026年2月26日
更新
2026年11月11日
篇幅
约 5 分钟
题目
P4374

版本

  1. v2当前
  2. v1

看到是紫题有点害怕,结果想了想发现是板子。

本题解采用树剖套线段树。

题意是给出一棵树和一些带边权的额外边,要求依次回答去掉每一条树边后,若选取一条额外边使得树仍联通,选取边的边权最小是多少。无解输出 -1。

我们发现,每次加入一条额外边,假设两端点分别为 x 和 y,那么这条边会和原来树上 x 和 y 之间的链构成一个环。这个环上任何一条树边被断,断开的两个连通块一定可以通过我们刚加的这条额外边保持联通。而且如果一条树边不在这个环上,那么断了这条树边,这条额外边也无法使树保持联通。这个显然吧。

因此我们可以边转点。在点的时间戳上建立线段树,线段树每片叶子维护“删掉这个点所代表的边后,使树联通需要的最短边的边权”。区间信息都不用合并,因为是单点查询。

这样我们每次读入一条两端点分别为 x 和 y ,权值为 k 的额外边,常规树剖写法,在树上以 x 和 y 为端点的链上进行和 k 取 min。

查询的时候先得到这条边对应的点,然后单点查询即可。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=100010,INF=1000000100;
int n,m;
int head[N],nex[N*2],to[N*2],cnt;
void add(int x,int y){
	cnt++;
	nex[cnt]=head[x];
	to[cnt]=y;
	head[x]=cnt;
}
int fa[N],dep[N],tp[N],sz[N],son[N],tot,dfn[N];
void dfs1(int x,int f){
	fa[x]=f;
	dep[x]=dep[f]+1;
	sz[x]=1;
	int maxn=-1;
	for(int i=head[x];i;i=nex[i]){
		int y=to[i];
		if(y==f)
			continue;
		dfs1(y,x);
		sz[x]+=sz[y];
		if(sz[y]>maxn){
			maxn=sz[y];
			son[x]=y;
		}
	}
}
void dfs2(int x,int top){
	tp[x]=top;
	tot++;
	dfn[x]=tot;
	if(son[x])
		dfs2(son[x],top);
	for(int i=head[x];i;i=nex[i]){
		int y=to[i];
		if(y==fa[x]||y==son[x])
			continue;
		dfs2(y,y);
	}
}
struct ST{
	int minn;
	int tag;
}st[N*4];
struct Edge{
	int x;
	int y;
}g[N];
int res;
inline int min(int x,int y){
	if(x<y)
		return x;
	return y;
}
void push_down(int root,int l,int r){
	int k=st[root].tag;
	st[root].tag=INF;
	st[root*2].minn=min(st[root*2].minn,k);
	st[root*2+1].minn=min(st[root*2+1].minn,k);
	st[root*2].tag=min(st[root*2].tag,k);
	st[root*2+1].tag=min(st[root*2+1].tag,k);
}
void change(int root,int l,int r,int x,int y,int k){
	if(l>=x&&r<=y){
		st[root].minn=min(st[root].minn,k);
		st[root].tag=min(st[root].tag,k);
		return;
	}
	if(l!=r&&st[root].tag!=INF)
		push_down(root,l,r);
	int mid=(l+r)/2;
	if(mid>=x)
		change(root*2,l,mid,x,y,k);
	if(mid+1<=y)
		change(root*2+1,mid+1,r,x,y,k);
}
void ask(int root,int l,int r,int x){
	if(l==r){
		res=st[root].minn;
		return;
	}
	if(l!=r&&st[root].tag!=INF)
		push_down(root,l,r);
	int mid=(l+r)/2;
	if(mid>=x)
		ask(root*2,l,mid,x);
	if(mid+1<=x)
		ask(root*2+1,mid+1,r,x);
}
int main(){
	cin>>n>>m;
	for(int i=1;i<n;i++){
		int x,y;
		cin>>x>>y;
		g[i].x=x;
		g[i].y=y;
		add(x,y);
		add(y,x);
	}
	dfs1(1,1);
	dfs2(1,1);
	for(int i=1;i<=n*4;i++)
		st[i].minn=st[i].tag=INF;
	for(int i=1;i<=m;i++){
		int x,y,k;
		cin>>x>>y>>k;
		while(tp[x]!=tp[y]){
			if(dep[tp[x]]<dep[tp[y]])
				swap(x,y);
			change(1,1,n,dfn[tp[x]],dfn[x],k);
			x=fa[tp[x]];
		}
		if(x!=y){
			if(dep[x]>dep[y])
				swap(x,y);
			change(1,1,n,dfn[x]+1,dfn[y],k);
		}
	}
	for(int i=1;i<n;i++){
		res=INF;
		ask(1,1,n,max(dfn[g[i].x],dfn[g[i].y]));
		if(res==INF)
			printf("-1\n");
		else
			printf("%d\n",res);
	}
	return 0;
}

原文
存档评论5 条抓取于