跳到正文

题解

[ABC361E] Tree and Hamilton Path 2 题解

Ame_wiki约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年7月9日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 3 分钟

版本

  1. v1当前

题目传送门:link。

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

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

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

∑(ui,vi,wi)∈Gwi−x{\displaystyle \sum_{(u_i,v_i,w_i)\in G}^{} w_i-x}

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

code

C++
#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 求直径。

原文