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
题意 跟hdu2196一毛一样。
树形dp题 比赛时候差一点就写完提交了。。。。 太可惜了,A了就有银牌了。
#include
#include
#include
#include
using namespace std;
const int MAXN=100100;
struct Node
{
int to;
int next;
int len;
}edge[MAXN*2];//因为存无向边,所以需要2倍
long long head[MAXN];//头结点
long long tol;
long long maxn[MAXN];//该节点往下到叶子的最大距离
long long smaxn[MAXN];//次大距离
long long maxid[MAXN];//最大距离对应的序号
long long smaxid[MAXN];//次大的序号
void init()
{
tol=0;
memset(head,-1,sizeof(head));
}
void add(int a,int b,int len)
{
edge[tol].to=b;
edge[tol].len=len;
edge[tol].next=head[a];
head[a]=tol++;
edge[tol].to=a;
edge[tol].len=len;
edge[tol].next=head[b];
head[b]=tol++;
}
//求结点v往下到叶子结点的最大距离
//p是v的父亲结点
void dfs1(int u,int p)
{
maxn[u]=0;
smaxn[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(v==p)continue;//不能往上找父亲结点
dfs1(v,u);
if(smaxn[u]if(smaxn[u]>maxn[u])
{
swap(smaxn[u],maxn[u]);
swap(smaxid[u],maxid[u]);
}
}
}
}
//p是u的父亲结点,len是p到u的长度
void dfs2(int u,int p)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(v==p)continue;
if(v==maxid[u])
{
if(edge[i].len+smaxn[u]>smaxn[v])
{
smaxn[v]=edge[i].len+smaxn[u];
smaxid[v]=u;
if(smaxn[v]>maxn[v])
{
swap(smaxn[v],maxn[v]);
swap(smaxid[v],maxid[v]);
}
}
}
else
{
if(edge[i].len+maxn[u]>smaxn[v])
{
smaxn[v]=edge[i].len+maxn[u];
smaxid[v]=u;
if(smaxn[v]>maxn[v])
{
swap(smaxn[v],maxn[v]);
swap(maxid[v],smaxid[v]);
}
}
}
dfs2(v,u);
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int n;
int u,v,len;
while(scanf("%d",&n)!=EOF)
{
init();
for(int i=2;i<=n;i++)
{
scanf("%d%d%d",&u,&v,&len);
add(u,v,len);
}
dfs1(1,-1);
dfs2(1,-1);
long long sum=0;
long long maxs=-1;
for(int i=1;i<=n;i++)
{
sum+=maxn[i];
maxs=max(maxs,maxn[i]);
}
cout<return 0;
}