nowcoder 水图 (DFS)

本文介绍了一个图论游戏的算法实现,旨在通过遍历无向联通图找到从指定起点出发并经过所有节点至少一次的最短路径。具体方法包括使用深度优先搜索(DFS)确定最大边权值,进而计算总路径长度。

水图
题目描述

小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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值