Highway
In ICPCCamp there were n towns conveniently numbered with 1,2,…,n connected with (n−1) roads. The i-th road connecting towns ai and bi has length ci. It is guaranteed that any two cities reach each other using only roads.
Bobo would like to build (n−1) highways so that any two towns reach each using only highways. Building a highway between towns x and y costs him δ(x,y) cents, where δ(x,y) is the length of the shortest path between towns x and y using roads.
As Bobo is rich, he would like to find the most expensive way to build the (n−1) highways.
Input
The input contains zero or more test cases and is terminated by end-of-file. For each test case:
The first line contains an integer n. The i-th of the following (n−1) lines contains three integers ai, bi and ci.
1≤n≤105
1≤ai,bi≤n
1≤ci≤108
The number of test cases does not exceed 10.
Output
For each test case, output an integer which denotes the result.
Sample Input
5
1 2 2
1 3 1
2 4 2
3 5 1
5
1 2 2
1 4 1
3 4 1
4 5 2
Sample Output
19
15
官方题解:
首先有一点得知道,关于树的直径
树的直径是指树上权值和最大的路径(最简单路径,即每一个点只经过一次)
存在结论:对于树上的任意一个节点,距离这个节点最远的距离一定是到直径的端点的距离
就是先求出树的最远点对(树的直径的端点)d1,d2,再求出以直径的两个端点为起点的dis[i](起点到i的距离),首先将直径(d1,d2的距离)加入集合,对于其他点i,加入max(d1到i的距离,d2到i的距离)到集合,集合所构成的树就是题目的答案(具体详见代码)
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=100010;
LL disd1[maxn],disd2[maxn];
int head[maxn];
bool vis[maxn];
struct edge
{
int to,next;
LL w;
} E[maxn*2];
int len,n;
void dfs(int st,LL w,LL dis[])
{
vis[st]=true;
dis[st]=w;
for(int i=head[st]; ~i; i=E[i].next)
{
if(!vis[E[i].to])
dfs(E[i].to,w+E[i].w,dis);
}
}
void add_edge(int u,int v,LL w)//邻接表建边
{
E[len].to=v;
E[len].w=w;
E[len].next=head[u];
head[u]=len++;
}
int main()
{
while(~scanf("%d",&n))
{
memset(disd1,0,sizeof(disd1));
memset(disd2,0,sizeof(disd2));
memset(head,-1,sizeof(head));
int u,v,w;
len=0;
for(int i=1; i<n; ++i)
{
scanf("%d%d%d",&u,&v,&w);
add_edge(u,v,w);
add_edge(v,u,w);
}
memset(vis,false,sizeof(vis));
dfs(1,0,disd1);//求出树的直径
int d1,d2;
LL maxx=0;
for(int i=1; i<=n; ++i)//寻找树的直径的第一个端点
if(disd1[i]>maxx)
maxx=disd1[i],d1=i;
memset(vis,false,sizeof(vis));
dfs(d1,0,disd1);//更新每个点到第一个端点的距离
maxx=0;
for(int i=1; i<=n; ++i)//寻找树的直径的第二个端点
if(disd1[i]>maxx)
maxx=disd1[i],d2=i;
memset(vis,false,sizeof(vis));
dfs(d2,0,disd2);//更新每个点到第二个端点的距离
LL ans=disd1[d2];
for(int i=1; i<=n; ++i)//加入边,建树
if(i!=d1&&i!=d2)
ans+=max(disd1[i],disd2[i]);
printf("%I64d\n",ans);
}
return 0;
}
参考博客:
爱种树的码农
w571523631