树上dp,样例过了,测试点全WA,在此求助!
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=5e5+10;
ll max_dis,ans;
ll dis[N],book[N],lvs[N];
struct T {
ll node,edge;
}temp;
vector <T> G[N];
void find_maxdis(int step){
book[step]=1;
max_dis=max(max_dis,dis[step]);
for(int i=0;i<G[step].size();i++)
if(book[G[step][i].node]==0)
book[G[step][i].node]=1,
dis[G[step][i].node]=dis[step]+G[step][i].edge,
find_maxdis(G[step][i].node);
}
void book_leaves(int step){
bool flag=true;
book[step]=1;
for(int i=0;i<G[step].size();i++)
if(book[G[step][i].node]==0)
flag=false,
book_leaves(G[step][i].node);
if(flag) lvs[step]=1;
}
ll program(int step){
book[step]=1;
ll max_len=0;
for(int i=0;i<G[step].size();i++)
if(book[G[step][i].node]==0)
max_len=max(max_len,(lvs[G[step][i].node]==0?program(G[step][i].node):G[step][i].edge));
for(int i=0;i<G[step].size();i++)
if(book[G[step][i].node]==0){
ans+=max_len-G[step][i].edge;
G[step][i].edge=max_len;
}
return max_len;
}
int main()
{
ll n,S,u,v,w;
cin>>n>>S;
for(int i=1;i<=n-1;i++){
cin>>u>>v>>w;
temp.node=v,temp.edge=w; G[u].push_back(temp);
temp.node=u,temp.edge=w; G[v].push_back(temp);
}
memset(book,0,sizeof(book));
find_maxdis(S);
memset(book,0,sizeof(book));
book_leaves(S);
memset(book,0,sizeof(book));
program(S);
cout<<ans<<endl;
return 0;
}
谢谢您的帮助