跳到正文

题解

题解:P14076 [GESP202509 六级] 货物运输

yedalong约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
题目
P14076

版本

  1. v2当前
  2. v1

Solution

很容易发现,该题目给出的图是一棵树。首都为 11,可以看作根为 11。

题目的要求是每个点都走一遍,求最少路径。假如最终要回到首都,那么结果就是所有边权的和再乘上 22,但是题目说可以不回到首都,这就说明最优情况下我们最后是停在叶子上的,那么少走的路径就是从叶子一直到根的距离,由于要路劲最小,那么贪心一下,选择距离最长的那个叶子作为最后的位置即可。

时间复杂度 O(n)O(n)。

AC code

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n,x,y,z,ans,maxx;
vector<pair<int,int>> edge[100005];
void dfs(int now,int fa,int sum){
	for(auto to:edge[now]) if(to.first!=fa) dfs(to.first,now,sum+to.second);
	maxx=max(maxx,sum);
}
signed main(){
	cin>>n;
	for(int i = 1;i<n;i++) cin>>x>>y>>z,edge[x].push_back({y,z}),edge[y].push_back({x,z}),ans+=z*2;
	dfs(1,0,0);
	cout<<ans-maxx;
	return 0;
}
原文