社区讨论

WA 4、5,我不理解

P1364医院设置参与者 1已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@lo97l1iw
此快照首次捕获于
2023/10/28 06:52
2 年前
此快照最后确认于
2023/10/28 06:52
2 年前
查看原帖
用树的重心做的。
为什么 WA 了第四个和第五个点。下载了数据和题解对了一下应该是树的重心找找错了,但是为什么?
代码找树的重心应该是没错的啊,是学习 OI Wiki - 树的重心 的。
这个代码在 P1395 - 会议通过的
我不理解。
CPP
#include<bits/stdc++.h>
#define INF 2147483647
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef const long long cll;
const int N = 500010;
ll n;
struct Edge {
    ll to, next;
    Edge() {}
} edge[N];
ll head[N], cnt = 0;
void add(cll &u, cll &v) {
    edge[++cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt;
}
ll size[N], weight[N], centroid[2] = {0, INF};
void GetCentroid(cll &father, cll &step) {
    size[step] = 1;
    weight[step] = 0;
    for(ll i = head[step]; i; i = edge[i].next) {
        if(edge[i].to != father) {
            GetCentroid(step, edge[i].to);
            size[step] += size[edge[i].to];
            weight[step] = max(weight[step], size[edge[i].to]);
        }
    }
    weight[step] = max(weight[step], n - size[step]);
    if(weight[step] <= (n >> 1)) {
        centroid[centroid[0] != 0] = step;
    }
}
ll sum = 0, wi[N];
void GetDistance(cll &father, cll &step, cll &num) {
    sum += num * wi[step];
    for(ll i = head[step]; i; i = edge[i].next) {
        if(edge[i].to != father) {
            GetDistance(step, edge[i].to, num + 1);
        }
    }
}
int main() {
    ll w, u, v;
    scanf("%lld", &n);
    for(ll i = 1; i <= n; i++) {
        scanf("%lld%lld%lld", &w, &u, &v);
        wi[i] = w;
        if(u != 0) { add(i, u); add(u, i); }
        if(v != 0) { add(i, v); add(v, i); }
    }
    GetCentroid(0, 1);
    GetDistance(0, centroid[0], 0);
    ll ans = sum;
    if(centroid[1] != INF) {
        sum = 0;
        GetDistance(0, centroid[1], 0);
        ans = min(ans, sum);
    }
    printf("%lld\n", ans);
    return 0;
}

回复

2 条回复,欢迎继续交流。

正在加载回复...