跳到正文

题解

P8855 [POI 2002] 商务旅行 题解

thy001约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年10月6日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

P8855 [POI 2002] 商务旅行

思路:

因为这个地图其实是一棵树,所以我们可以用树来存贮它。并且在后期求时间时,因为每条路都是需要1个时间单位,所以就可以用边LCA求。(S=dep[l]+dep[r]−2∗dep[LCA(l,r)]S=dep[l]+dep[r]-2*dep[LCA(l,r)])

时间复杂度:O((N+M)logN)O((N+M)logN) //n代表的是节点数量,m的询问次数

空间复杂度:O(NlogN)O(NlogN)

代码&注释:

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=5e5+5;
ll n,m,x,y,a,b,fa[N][25],dep[N],l,r,ans;
vector<ll>G[N];
void dfs(ll r,ll l,ll d){
	dep[r]=d,fa[r][0]=l;
	for(ll i=1;i<=20;i++)
		fa[r][i]=fa[fa[r][i-1]][i-1];
	for(auto q:G[r])
		if (q!=l)
			dfs(q,r,d+1);
}
ll lca(ll r,ll l){
	if(dep[r]<dep[l]) swap(r,l);
	for(ll i=20;i>=0;i--)
		if(dep[r]-(1<<i)>=dep[l])
			r=fa[r][i];
	if(r==l) return r;
	for(ll i=20;i>=0;i--)
		if(fa[r][i]!=fa[l][i])
			r=fa[r][i],l=fa[l][i];
	return fa[r][0];
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n;
	for(ll i=1;i<n;i++){
		cin>>x>>y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	dfs(1,0,1);								//遍历
	cin>>m>>l;
	for(int i=2;i<=m;i++){					//顺次求就行
		cin>>r;
		ans+=dep[l]+dep[r]-2*dep[lca(l,r)];	//边LCA
		l=r;
	}
	cout<<ans;
	return 0;
}
原文