记录一下叶子节点到根节点的距离
f[i]
,
通过一遍
dfs
找出每一个节点中子树修改的最小值
opt[i]
,
然后再用一遍
dfs
把标记下传,最后加一遍就可以了
ps:可能只有我用了三遍
dfs
…
我还是太菜了
#include <cstdio>
using namespace std;
template <class T>T Max(const T &a, const T &b) {return a > b ? a : b;}
template <class T>T Min(const T &a, const T &b) {return a < b ? a : b;}
typedef long long LL;
const int SN = 500000 + 10;
const int inf = 0x3f3f3f3f;
LL f[SN], head[SN], n, root, opt[SN], num, u, v, w, maxn[SN], ans[SN], maxx, res;
struct Edge {
int u,v,next;LL w;
}E[SN<<1];
void Read(LL &x) {
LL in = 0,f = 1;char ch = getchar();
while(ch<'0' || ch>'9') {if(ch=='-') f = -1; ch = getchar();}
while(ch>='0' && ch<='9') {in = in*10+ch-'0';ch = getchar();}
x = in*f;
}
void Add(int u,int v,LL w) {
E[++num].u = u;
E[num].v = v;
E[num].w = w;
E[num].next = head[u];
head[u] = num;
}
void dfs1(int u,int fa) {
for(int i = head[u]; i; i = E[i].next) {
int to = E[i].v;
if(to == fa) continue;
f[to] = f[u] + E[i].w;maxx = Max(maxx, f[to]);
dfs1(to,u);
}
}
void dfs2(int u,int fa) {
int cnt = 0;LL minn = inf;
for(int i = head[u]; i; i = E[i].next) {
int to = E[i].v;
if(to == fa) continue;cnt++;
dfs2(to,u);
minn = Min(minn, opt[to]);
}
if(cnt == 0) opt[u] = ans[u] = maxx - f[u];
else opt[u] = ans[u] = minn;
}
void dfs3(int u,int fa) {
bool flag = 0;
for(int i = head[u]; i; i = E[i].next) {
int to = E[i].v;
if(to == fa) continue;
ans[to] -= opt[u];flag = 1;
dfs3(to,u);
}
}
int main() {
Read(n),Read(root);
for(int i = 1; i < n; i++) {
Read(u),Read(v),Read(w);
Add(u,v,w),Add(v,u,w);
}
dfs1(root,0);
dfs2(root,0);
dfs3(root,0);
for(int i = 1; i <= n; i++) res+=ans[i];
printf("%lld\n",res);
return 0;
}