[ABC361E] Tree and Hamilton Path 2 题解

· · 题解

题目传送门:link。

思路:对于一棵树(如图),直径为 16,路径 6 \Rightarrow 5 \Rightarrow 2 \Rightarrow 4 \Rightarrow 2 \Rightarrow 1 \Rightarrow 7 \Rightarrow 1 \Rightarrow 3。

可以发现,我们是沿直径(6 到 3)走,碰见一个分叉就往返一次,总和为 \sum_{}^{}w_i \times 2 - 直径。

故答案为(x 为直径长度):

{\displaystyle \sum_{(u_i,v_i,w_i)\in G}^{} w_i-x}

这里由于是无向图,所以 w_i 存的时就是双倍的。

code

#include<bits/stdc++.h>
using namespace std;
const int N=4e5+5;
#define int long long
#define endl "\n"
struct node{
    int to,ne,ver;
}e[N];
queue<int> q;
int n,he[N],dis[N],vis[N],tot,res;
void cleaning(){ memset(vis,0,sizeof(vis)); memset(dis,0,sizeof(dis)); while(!q.empty()) q.pop(); }
void add(int x,int y,int z){
    e[++tot].ne=he[x];
    e[tot].to=y;
    e[tot].ver=z;
    he[x]=tot;
}
int bfs(int xxs){
    cleaning();
    int maxx=0,mno;
    vis[xxs]=1;
    q.push(xxs);
    while(!q.empty()){
        int x=q.front();
        q.pop();
        for(int i=he[x];i!=-1;i=e[i].ne){
            int y=e[i].to;
            if(vis[y]) continue;
            vis[y]=1;
            dis[y]=dis[x]+e[i].ver;
            q.push(y);
            if(dis[y]>maxx){
                mno=y;
                maxx=dis[y];
            }
        }
    }
    return mno;
}
signed main(){
    cleaning();
    memset(he,-1,sizeof(he));
    cin>>n;
    int x,y,z;
    for(int i=1;i<=n-1;i++){
        cin>>x>>y>>z;
        add(x,y,z);
        add(y,x,z);
        res+=z*2;
    }
    int ak=bfs(1);
    int au=bfs(ak);
    int num=0;
    num=dis[au];
    cout<<res-num;
    return 0;
}

这里我跑的是 bfs 求直径。