题面简述
给定以\(s\)为根的一棵树,可以进行代价为1的操作使一条边权+1,求最小代价使得根节点到所有叶子节点距离相等。
分析
令\(sum[x]\)表示以\(x\)为子树的最大距离(根->叶子)。先处理\(sum[x]\),再从根节点开始调整直到遍历到叶节点来计算总代价;
假设\(x\)已调整完毕,对于子节点\(u\),将以其为根的子树调整到最大距离\(sum[x]\)的代价是\(sum[x]-(sum[u]+val[i])\),总代价就是:
\[\sum_{u,v \in E} sum[x]-(sum[u]+val[i]) \]Code
#include<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
const int maxn = 5e5 + 10;
int nxt[maxn], to[maxn], head[maxn], val[maxn];
int tot;
ll sum[maxn], ans;
int n, s;
int a, b, t;
void dfs1(int x, int fa) {
for (int i = head[x]; i; i = nxt[i]) {
int u = to[i];
if (u == fa) continue;
dfs1(u, x);
sum[x] = std::max(sum[x], sum[u] + val[i]);
}
}
void dfs2(int x, int fa) {
for (int i = head[x]; i; i = nxt[i]) {
int u = to[i];
if (u == fa) continue;
dfs2(u, x);
ans += sum[x] - (sum[u] + val[i]);
}
}
void add(int u, int v, int w) {
to[++tot] = v;
val[tot] = w;
nxt[tot] = head[u];
head[u] = tot;
}
int main() {
scanf("%d%d", &n, &s);
for (int i = 1; i <= n - 1; i++) {
scanf("%d%d%d", &a, &b, &t);
add(a, b, t);
add(b, a, t);
}
dfs1(s, 0);
dfs2(s, 0);
printf("%lld", ans);
}
标签:时态,head,val,int,sum,tot,maxn,ZJOI2007,dp
From: https://www.cnblogs.com/MrWangnacl/p/16908447.html