发现题目要求的相当于是在一颗树上面求(dis(A,B)+min(dis(A,C),dis(B,C)))
显然我们要最大化这个,前面的一定要是直径,后面那个直接随便乱求就行了。
/*
mail: mleautomaton@foxmail.com
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define re register
#define int ll
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=200010;
int n,m,front[N],cnt,dis1[N],dis2[N],vis[N];
struct node{int to,nxt,w;}e[N<<1];
void Add(int u,int v,int w){e[++cnt]=(node){v,front[u],w};front[u]=cnt;}
typedef pair<int,int> pii;
#define mp make_pair
priority_queue<pii,vector<pii>,greater<pii> >q;
void bfs1(int s){
memset(dis1,63,sizeof(dis1));memset(vis,0,sizeof(vis));
dis1[s]=0;
q.push(mp(0,s));
while(!q.empty()){
int u=q.top().second;q.pop();
if(vis[u])continue;vis[u]=1;
for(int i=front[u];i;i=e[i].nxt){
int v=e[i].to;
if(dis1[v]>dis1[u]+e[i].w){
dis1[v]=dis1[u]+e[i].w;
q.push(mp(dis1[v],v));
}
}
}
}
void bfs2(int s){
memset(dis2,63,sizeof(dis2));memset(vis,0,sizeof(vis));
dis2[s]=0;
q.push(mp(0,s));
while(!q.empty()){
int u=q.top().second;q.pop();
if(vis[u])continue;vis[u]=1;
for(int i=front[u];i;i=e[i].nxt){
int v=e[i].to;
if(dis2[v]>dis2[u]+e[i].w){
dis2[v]=dis2[u]+e[i].w;
q.push(mp(dis2[v],v));
}
}
}
}
signed main(){
n=gi();m=gi();
for(int i=1;i<=m;i++){
int u=gi(),v=gi(),w=gi();
Add(u,v,w);Add(v,u,w);
}
bfs1(1);
int mx=0,id1=0,id2=0;
for(int i=1;i<=n;i++)
if(dis1[i]>mx){mx=dis1[i];id1=i;}
bfs1(id1);mx=0;
for(int i=1;i<=n;i++)
if(dis1[i]>mx){mx=dis1[i];id2=i;}
int ans=0;
bfs2(id2);
for(int i=1;i<=n;i++)
ans=max(ans,min(dis1[i],dis2[i]));
printf("%lld
",mx+ans);
return 0;
}