Codeforces Round #359 (Div. 2)D. Kay and Snowflake

题意:给定一棵以1为根的n个节点的树,然后m个询问,每次询问给定一个x。求在x为根的子树中的质心是谁。x的质心:在这颗子树中删掉它的质心,然后变成若干课小树,要求小树中的最大的size要<=x的size/2。

分析:我们直接预处理出每个点的质心,很容易想到x的质心一定在x和x的size最大的儿子的质心的路径上。为什么呢?画画图就知道了,不解释。然后我们只要dfs处理一遍就行啦。

求解时,从儿子节点的ans值向上找父节点,直到满足要求。
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define L(i) i<<1
#define R(i) i<<1|1
#define INF  0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-9
#define maxn 1000100
#define MOD 1000000007

struct Edge
{
    int to,next;
} edge[maxn];
int n,m,num[maxn],ans[maxn];
int tot,head[maxn],pre[maxn];
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
}
void add_edge(int u,int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}
void dfs(int u)
{
    num[u] = 1;
    ans[u] = u;
    int mx = 0,tmp = u;
    if(head[u] == -1)
        return;
    for(int i = head[u]; i != -1; i = edge[i].next)
    {
        int v = edge[i].to;
        dfs(v);
        num[u] += num[v];
        if(num[v] > mx)
        {
            mx = num[v];
            tmp = v;
        }
    }
    ans[u] = ans[tmp];
    while(ans[u] != u && num[u] - num[ans[u]] > num[u]/2)
        ans[u] = pre[ans[u]];
}
int main()
{
    int t;
    //scanf("%d",&t);
    while(scanf("%d%d",&n,&m) != EOF)
    {
        init();
        for(int i = 2; i <= n; i++)
        {
            int x;
            scanf("%d",&x);
            pre[i] = x;
            add_edge(x,i);
        }
        dfs(1);
        while(m--)
        {
            int x;
            scanf("%d",&x);
            printf("%d\n",ans[x]);
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值