CF1042F Leaf Sets

CF1042F Leaf Sets

题意翻译

给定一棵\(n\)个点的树,将叶子节点分为数个集合使集合里点对最长距离不超过\(k\),求最少集合数。

输入输出格式

输入格式:

The first line contains two integers \(n\) and \(k\) ( \(3 \le n \le 10^6\) ) — the number of vertices in the tree and the maximum distance between any pair of leaves in each beautiful set.

Each of the next \(n - 1\) lines contains two integers \(v_i\) and \(u_i\) ( \(1 \le v_i, u_i \le n\) ) — the description of the \(i\) -th edge.

It is guaranteed that the given edges form a tree.

输出格式:

Print a single integer — the minimal number of beautiful sets the split can have.


洛谷难度标签是假的系列(2018.10.12)。

有一定的思维难度,但不至于。

考虑这样一个性质:
如果有两个叶子它们互为最近的叶子,那么它们对树中其他叶子的距离是较深的那个叶子的贡献。

在这个题,如果它们之间的距离没有超过k,那么浅的叶子是没有用的,如果超过了,让深的叶子自成一派,浅的留下向上的可能性,这样就是对的。

具体的说,我们在外部统计答案,然后对以一个度数大于1的节点为根进行遍历。

每颗子树把从它儿子来的深叶子的贡献排序,然后判断有没有深的叶子不合法了,有就删掉,然后传上去最大的没被删的。


Code:

#include <cstdio>
#include <vector>
#include <algorithm>
const int N=1e6+10;
int head[N],to[N<<1],Next[N<<1],cnt;
void add(int u,int v)
{
    to[++cnt]=v,Next[cnt]=head[u],head[u]=cnt;
}
int n,k,ans,in[N];
int dfs(int now,int fa)
{
    std::vector <int > diss;
    for(int i=head[now];i;i=Next[i])
    {
        int v=to[i];
        if(v==fa) continue;
        diss.push_back(dfs(v,now));
    }
    std::sort(diss.begin(),diss.end());
    int i;
    for(i=diss.size()-1;i>0;i--)
    {
        if(diss[i]+diss[i-1]>k) ++ans;
        else break;
    }
    return i<0?in[now]==1:diss[i]+1;
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int u,v,i=1;i<n;i++)
    {
        scanf("%d%d",&u,&v);
        add(u,v),add(v,u);
        ++in[v],++in[u];
    }
    for(int i=1;i<=n;i++)
        if(in[i]>1)
        {
            if(dfs(i,0)) ans++;
            break;
        }
    printf("%d\n",ans);
    return 0;
}

2018.10.12

转载于:https://www.cnblogs.com/butterflydew/p/9778274.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值