Problem Statement
There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices Ai and Bi and has a length of Ci.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above.
Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path.
Notes
A Hamiltonian path in a graph is a path in the graph that visits each vertex exactly once.
Constraints
2≤N≤105
1≤Ai
题目大意
给出一棵树,根据这棵树,建出一个完全图,
两个点之间的边权就是树上路径长度。
求最长哈密尔顿回路。
题解
考虑最优的策略,
围绕着树的重心,在每棵子树上跑,
这样每条边就会被利用两次。
但有一条边除外:
1、如果这棵树上有两个重心,
很显然连接在两个重心之间的边就无法被利用两次。
2、如果只有一个重心,按照最优策略,
让连接重心中边权最小的一条边只跑一次。
code
#include<queue>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <time.h>
#define ll long long
#define N 100003
#define M 103
#define db double
#define P putchar
#define G getchar
#define inf 998244353
using namespace std;
char ch;
void read(int &n)
{
n=0;
ch=G();
while((ch<'0' || ch>'9') && ch!='-')ch=G();
ll w=1;
if(ch=='-')w=-1,ch=G();
while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
n*=w;
}
int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
ll abs(ll x){return x<0?-x:x;}
ll sqr(ll x){return x*x;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}
int nxt[N*2],to[N*2],v[N*2],lst[N],tot;
int n,x,y,z,m,pos,si[N];
ll ans,mi;
void ins(int x,int y,int z)
{
nxt[++tot]=lst[x];
to[tot]=y;
v[tot]=z;
lst[x]=tot;
}
void dfs(int x,int fa)
{
int mx=0;
si[x]=1;
for(int i=lst[x];i;i=nxt[i])
if(to[i]!=fa)dfs(to[i],x),si[x]+=si[to[i]],mx=max(mx,si[to[i]]);
mx=max(mx,n-si[x]);
if(mx<m)m=mx,pos=x;
}
void dfs1(int x,int fa,ll len)
{
si[x]=1;
ans+=len;
for(int i=lst[x];i;i=nxt[i])
if(to[i]!=fa)dfs1(to[i],x,len+v[i]),si[x]+=si[to[i]];
}
int main()
{
read(n);
for(int i=1;i<n;i++)
read(x),read(y),read(z),ins(x,y,z),ins(y,x,z);
m=n;mi=2147483647;
dfs(1,0);
dfs1(pos,0,0);
for(int i=lst[pos];i;i=nxt[i])
if(si[to[i]]==(n+1)/2)
{
mi=v[i];
break;
}
else mi=min(mi,v[i]);
write(ans*2-mi);
return 0;
}