【AcWing——深度优先搜索】AcWing 846. 数的重心

AcWing 846. 数的重心

在这里插入图片描述
用数组进行邻接表存储方式,然后使用DFS进行图的遍历。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010, M = N * 2;

int n;
int h[N], e[M], ne[M], idx;
int ans = N;//全局变量,存最终结果
bool st[N];

void add(int a, int b) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

//返回以u为节点的子树的节点个数
int dfs(int u) {
    st[u] = true;
    
    int size = 0, sum = 0;//size保存除根节点u外,子树的最大节点个数;sum保存连同根节点在内的节点个数
    for (int i = h[u]; i != -1; i = ne[i]) {
        int j = e[i];
        if (st[j]) continue;
        
        int s = dfs(j);
        size = max(size, s);
        sum += s;
    }
    
    size = max(size, n - sum - 1);//整个树中,除去以u为根节点的树的节点个数
    ans = min(ans, size);
    
    return sum + 1;
}

int main() {
    scanf("%d", &n);
    
    memset(h, -1, sizeof h);
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        scanf("%d%d", &a, &b);
        add(a, b), add(b, a);
    }
    
    dfs(1);
    printf("%d\n", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值