【CF61D】Eternal Victory

题目大意:给定一棵 N 个节点的树,求从 1 号节点(根节点)出发,任意节点结束,且至少经过每个节点一次的最短路径是多少。

题解:首先考虑最终要回到根节点的情况,可以发现最短路径长度一定等于该树边权的 2 倍。因此,在任意一点结束只需在答案贡献中减掉该树的一条最长链即可。

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;

inline int read(){
    int x=0,f=1;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
    do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
    return f*x;
}

int n;
long long ans;
struct node{
    int nxt,to,w;
}e[maxn<<1];
int tot=1,head[maxn];
inline void add_edge(int from,int to,int w){
    e[++tot]=node{head[from],to,w},head[from]=tot;
}

void read_and_parse(){
    n=read();
    for(int i=1,x,y,z;i<n;i++){
        x=read(),y=read(),z=read();
        add_edge(x,y,z),add_edge(y,x,z);
        ans+=z<<1;
    }
}

long long dfs(int u,int fa){
    long long now=0;
    for(int i=head[u];i;i=e[i].nxt){
        int v=e[i].to;if(v==fa)continue;
        now=max(now,dfs(v,u)+e[i].w);
    }
    return now;
}

void solve(){
    printf("%lld\n",ans-dfs(1,0));
}

int main(){
    read_and_parse();
    solve();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wzj-xhjbk/p/10045605.html