牛客练习赛27【C 水图 dfs求最长路】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37867156/article/details/82808297

链接:https://www.nowcoder.com/acm/contest/188/C
来源:牛客网

题目描述

小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

题解:发现从 x 出发,只有一条路径可以只经过一次,其他的都会经过两次 。找出这条最长的路径,用所有路径权值之和*2,减去这条路径的就好了。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#define ll long long
#define INF 0x3f
using namespace std;
const int maxn = 50000+7;
int head[maxn], ver[maxn<<1];
ll edge[maxn<<1];
int Next[maxn];
int vis[maxn];
ll maxx;
int n, x;
int tot = 0;
ll ans = 0, sum = 0;
void add(int x, int y, ll z) {
    ver[++tot] = y, edge[tot] = z;
    Next[tot] = head[x];
    head[x] = tot;
}
void dfs(int x, int fa, ll step){
    maxx = max(step, maxx);
    for(int i = head[x]; i; i = Next[i]){
        if(ver[i] == fa) continue;
        dfs(ver[i], x, step+edge[i]);
    }
}

int main()
{
    int u, v;
    ll w;
    scanf("%d %d", &n, &x);
    for(int i = 0; i < n-1; i++){
        scanf("%d %d %lld", &u, &v, &w);
        add(u, v, w);
        add(v, u, w);
        ans += w;
    }
    dfs(x, 0, 0);
    printf("%lld\n", ans*2 - maxx);
    return 0;
}
/*
4 3
1 2 1
1 3 1
3 4 1
*/

猜你喜欢

转载自blog.csdn.net/qq_37867156/article/details/82808297
今日推荐