题目描述:
雾。
题目分析:
正解:树形DP
非正解:XJB DFS
记录maxtime[i]为以i为根的子树叶子节点距离i的最大时间
我们只需要用两次DFS即可求解答案
题目链接:
Ac 代码:
#include <iostream>
#include <cstdio>
#define ll long long
const int maxm=510000;
ll maxtime[maxm],ans,cost[maxm<<1];
int head[maxm],to[maxm<<1],net[maxm<<1],cnt;
int n,root;
inline void addedge(int u,int v,ll c)
{
cnt++;
to[cnt]=v,cost[cnt]=c,net[cnt]=head[u],head[u]=cnt;
}
void getdis(int now,int fa)
{
for(int i=head[now];i;i=net[i])
if(to[i]!=fa)
{
getdis(to[i],now);
maxtime[now]=std::max(maxtime[now],cost[i]+maxtime[to[i]]);
}
}
void getans(int now,int fa)
{
for(int i=head[now];i;i=net[i])
if(to[i]!=fa)
{
getans(to[i],now);
ans+=(maxtime[now]-maxtime[to[i]]-cost[i]);
}
}
int main()
{
scanf("%d%d",&n,&root);
for(int i=1;i<n;i++)
{
int u,v;
ll c;
scanf("%d%d%lld",&u,&v,&c);
addedge(u,v,c);
addedge(v,u,c);
}
getdis(root,0),getans(root,0);
printf("%lld\n",ans);
return 0;
}