POJ 1655 Balancing Act 树的重心

 树的重心定义:删除掉某个结点后,以这个结点的子节点为根的最大子树大小最小。

dp的思想,dfs过程类似树链刨分,有注释。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 2e4 + 10;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 11092019;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
struct Edge
{
    int before, to, w;
} e[maxn << 1];
int n, k, root, sum, head[maxn];
int size[maxn];  // 以这个点为根的子树大小
int max_p[maxn]; // 去掉这个点后最大的子树大小
void add(int u, int v)
{
    e[k].before = head[u];
    e[k].to = v;
    head[u] = k++;
}
void DFS(int u, int fa)
{
    size[u] = 1;
    max_p[u] = 0;
    for (int i = head[u]; i != -1; i = e[i].before)
    {
        int v = e[i].to;
        if (v == fa)
            continue;
        DFS(v, u);
        size[u] += size[v];
        if (size[v] > max_p[u])
            max_p[u] = size[v]; // 用子树大小更新max_p
    }
    max_p[u] = max(max_p[u], sum - size[u]); // 自己子树和回到根节点方向
    if (max_p[u] < max_p[root])              // 维护root 即max_p最小的点
        root = u;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    int T, a, b, c;
    cin >> T;
    while (T--)
    {
        cin >> n;
        memset(head, -1, sizeof head);
        k = 0;
        for (int i = 0; i < n - 1; i++)
        {
            cin >> a >> b;
            add(a, b);
            add(b, a);
        }
        root = 0;
        sum = max_p[root] = n;
        DFS(1, 0);
        cout << root << " " << max_p[root] << endl;
    }
    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值