水图
题目描述
小w不会离散数学,所以她van的图论游戏是送分的
小w有一张n个点n-1条边的无向联通图,每个点编号为1~n,每条边都有一个长度
小w现在在点x上
她想知道从点x出发经过每个点至少一次,最少需要走多少路
输入描述:
第一行两个整数 n,x,代表点数,和小w所处的位置
第二到第n行,每行三个整数 u,v,w,表示u和v之间有一条长为w的道路
输出描述:
一个数表示答案
示例1
输入
3 1
1 2 1
2 3 1
输出
2
备注
1 ≤ n ≤ 50000 , 1 ≤ w ≤ 2147483647
#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<string>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<set>
using namespace std;
const int maxn = 1e6 + 50;
const int MOD = 1e9 + 7;
const double eps = 1e-9;
const int INF=0x3f3f3f3f;
#define PI acos(-1)
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mem(a,b) memset(a,b,sizeof(a))
#define rep(i,x) for(int i=0;i<x;++i)
#define UP(i,x,y) for(int i=x;i<=y;i++)
#define DOWN(i,x,y) for(int i=x;i>=y;i--)
#define DEBUG(x) cout << "#: " << (x) << endl
using LL = long long;
using PII = pair<int,int>;
using VI = vector<int>;
using VPII = vector<PII>;
VPII G[maxn];
int n,x,mx,ans;
void dfs(int x,int f,int cur){
mx = max(mx,cur);
for(auto t : G[x]){
int v = t.first,w = t.second;
if(v != f) dfs(v,x,cur + w);
}
}
int main(){
IO;
ans = 0;
mx = 0;
cin >> n >> x;
for(int i = 0; i < n - 1; i++) {
int u,v,w; cin >> u >> v >> w;
G[u].push_back({v,w}); G[v].push_back({u,w});
ans += w;
}
dfs(x,0,0);
cout << 2 * ans - mx << endl;
return 0;
}
本文介绍了一个图论游戏的算法实现,旨在通过遍历无向联通图找到从指定起点出发并经过所有节点至少一次的最短路径。具体方法包括使用深度优先搜索(DFS)确定最大边权值,进而计算总路径长度。
1007

被折叠的 条评论
为什么被折叠?



