社区讨论
蒟蒻不理解,为什么都说这题和树的重心有关
P1364医院设置参与者 3已保存回复 2
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 2 条
- 当前快照
- 1 份
- 快照标识符
- @lu5l2xpf
- 此快照首次捕获于
- 2024/03/24 21:57 2 年前
- 此快照最后确认于
- 2024/03/25 12:49 2 年前
这不是个换根dp吗。。
CPP#include <bits/stdc++.h>
using namespace std;
inline int read() {
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9') if (c == '-') flag = true;
int res = c - '0';
while ((c = getchar()) >= '0' && c <= '9') res = (res << 3) + (res << 1) + c - '0';
return flag ? -res : res;
}
const int maxn = 110;
int n, dp[maxn], f[maxn], a[maxn], sum[maxn];
struct Edge {
int to, w, next;
} edge[maxn << 1];
int head[maxn << 1], cnt;
void init() {
for (int i = 0; i <= n; i++) head[i] = -1;
cnt = 0;
}
void add_edge(int u, int v, int w) {
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void dfs(int x, int fa) {
dp[x] = 0;
sum[x] = a[x];
for (int i = head[x]; ~i; i = edge[i].next) {
int y = edge[i].to;
if (y == fa) continue;
dfs(y, x);
dp[x] += dp[y] + sum[y];
sum[x] += sum[y];
}
}
void rfs(int x, int fa) {
for (int i = head[x]; ~i; i = edge[i].next) {
int y = edge[i].to;
if (y == fa) continue;
f[y] = f[x] + sum[1] - 2 * sum[y];
rfs(y, x);
}
}
int main() {
n = read();
init();
for (int i = 1; i <= n; ++i) {
a[i] = read();
int x = read(), y = read();
if (x) add_edge(x, i, 1), add_edge(i, x, 1);
if (y) add_edge(y, i, 1), add_edge(i, y, 1);
}
dfs(1, -1);
f[1] = dp[1];
rfs(1, -1);
int ans = 0x3f3f3f3f;
for (int i = 1; i <= n; ++i) ans = min(ans, f[i]);
printf("%d", ans);
return 0;
}
回复
共 2 条回复,欢迎继续交流。
正在加载回复...