Balancing Act [dfs][树dp]

14 篇文章 0 订阅

题意:一个树上删掉一个点,使得得到的森林中的最大数的size作为结果,最小化这个结果。即求树的重心。
思路:删掉当前节点,得到的最大的树的大小就是dfs序中它所有的儿子的大小和他父树中的大小的最大值。 一遍dfs即可得到sz[]

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<cstdlib>
#include<list>
#include<stack>
#include<cmath>
#include<iomanip>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
void debug() {cout << "ok running!" << endl;}
int n;
vector<int> mp[200005];
int sz[200005];
int ans, pos;
void dfs(int u, int v)
{
    sz[u] = 1;
    int res = 0;

    for(int i = 0; i < mp[u].size(); ++i)
    {
        int to = mp[u][i];
        if(to == v) continue;
        //cout << u << " " << v << " " << to << endl;
        dfs(to, u);
        sz[u] += sz[to];
        res = max(res, sz[to]);
    }
    res = max(res, n - sz[u]);
    if(res < ans || res == ans && u < pos)
        ans = res, pos = u;
}
int main()
{
    ios::sync_with_stdio(false);
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n;
        for(int i = 0; i <= n; ++i) mp[i].clear();
        for(int i = 0; i < n-1; ++i)
        {
            int x, y;
            cin >> x >> y;
            mp[x].push_back(y);
            mp[y].push_back(x);
        }
        ans = 0x3f3f3f3f;
        dfs(1, -1);
        cout << pos << " " << ans << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值