思路: 感觉这题是写过树上dp里面最水的一题了233
dp[rt]表示以rt为根的树,修改所需最小值.
具体过程看代码注释
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<math.h>
#include<set>
using namespace std;
#define LL long long
#define ULL unsigned long long
const int INF=0x3f3f3f3f;
const double eps=1e-5;
const int maxn=5e5+5;
struct
{
int to,w,next;
}edge[maxn];
int head[maxn],cnt=1;
int max_time[maxn];//以i为根的子树中,i的所有孩子所需的最大时间,通过dfs回溯来维护
LL dp[maxn];
int root,n;
void add(int from,int to,int w)
{
edge[cnt].to=to;
edge[cnt].w=w;
edge[cnt].next=head[from];
head[from]=cnt++;
}
void dfs(int rt,int par)
{
vector<int> time;//存所有孩子节点的权值
int mmax=0;//存孩子节点中的最大权值
for(int i=head[rt];i;i=edge[i].next)
{
int to=edge[i].to;
if(to==par) continue;
dfs(to,rt);
dp[rt]+=dp[to];
edge[i].w+=max_time[to];//根到i孩子的权值 加上max_time[i],就成了根到最远叶子的权值
time.push_back(edge[i].w);
mmax=max(mmax,edge[i].w);
}
max_time[rt]=mmax;
for(int i=0;i<time.size();i++) dp[rt]=dp[rt]+mmax-time[i];//把差值加上即可
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
// cout.tie(0);
scanf("%d%d",&n,&root);
for(int i=1;i<n;i++)
{
int v,u,w;
scanf("%d%d%d",&v,&u,&w);
add(v,u,w),add(u,v,w);
}
dfs(root,-1);
printf("%lld\n",dp[root]);
system("pause");
return 0;
}