跳到正文

题解

P8855 [POI 2002] 商务旅行

Rigel约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年6月22日
收录
2025年12月12日
更新
2026年10月30日
篇幅
约 4 分钟
获赞
22
题目
P8855

版本

  1. v1当前

题意

给定一棵 NN 个结点的树,所有边的权值均为 11。从结点 11 出发,依次经过 MM 个指定结点,求路径总长度的最小值。

思路

定义 dis⁡(x,y)\operatorname{dis}(x,y) 为 xx 与 yy 的距离,dep⁡(x)\operatorname{dep}(x) 为 xx 的深度(根结点 dep⁡(1)=0\operatorname{dep}(1) = 0),lca⁡(x,y)\operatorname{lca}(x,y) 为 xx 与 yy 的最近公共祖先。

结点 uu 与 vv 的距离为:

dis⁡(u,v)=dis⁡(u,lca⁡(u,v))+dis⁡(v,lca⁡(u,v))=dep⁡(u)−dep⁡(lca⁡(u,v))+dep⁡(v)−dep⁡(lca⁡(u,v))=dep⁡(u)+dep⁡(v)−2×dep⁡(lca⁡(u,v)).\begin{aligned} \operatorname{dis}(u,v) &= \operatorname{dis}(u,\operatorname{lca}(u,v)) + \operatorname{dis}(v,\operatorname{lca}(u,v))\\ &= \operatorname{dep}(u) - \operatorname{dep}(\operatorname{lca}(u,v)) + \operatorname{dep}(v) - \operatorname{dep}(\operatorname{lca}(u,v))\\ &= \operatorname{dep}(u) + \operatorname{dep}(v) - 2 \times \operatorname{dep}(\operatorname{lca}(u,v)). \end{aligned}

树剖。查询时求 LCA 即可。

时间复杂度为 O(N+Mlog⁡N)\mathcal{O}(N + M \log N)。

Code

C++
#include<bits/stdc++.h>
#define int long long
#define maxn 30010

using namespace std;

int n,m,tot,tim,lnk[maxn],lst=1,ans;

struct node{
	int dep,siz,fa,hson,top;
}a[maxn];

struct edge{
	int to,nxt;
}e[maxn<<1];

inline int read(){
	int ret=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9')ret=ret*10+(ch&15),ch=getchar();
	return ret*f;
}

void add_e(int x,int y){
	e[++tot]=(edge){y,lnk[x]};
	lnk[x]=tot;
}

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

void dfs2(int u,int top){
	a[u].top=top;
	if(a[u].hson){
		dfs2(a[u].hson,top);
		for(int i=lnk[u];i;i=e[i].nxt){
			int v=e[i].to;
			if(v==a[u].fa||v==a[u].hson)continue;
			dfs2(v,v);
		}
	}
}

int lca(int u,int v){
	while(a[u].top!=a[v].top){
		if(a[a[u].top].dep<a[a[v].top].dep)swap(u,v);
		u=a[a[u].top].fa;
	}
	return a[u].dep<a[v].dep?u:v;
}

int qry(int u,int v){
	return a[u].dep+a[v].dep-(a[lca(u,v)].dep<<1);
}

signed main(){
	n=read();
	for(int i=1;i^n;i++){
		int u=read(),v=read();
		add_e(u,v),add_e(v,u);
	}
	dfs1(1,0),dfs2(1,1);
	m=read();
	while(m--){
		int x=read();
		ans+=qry(lst,x);
		lst=x;
	}
	printf("%lld\n",ans);
	return 0;
}
原文
存档评论5 条抓取于