zoukankan      html  css  js  c++  java
  • 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
    ",ans);
        return 0;
    }
    

    2018.10.12

  • 相关阅读:
    Two Sum II
    Subarray Sum
    Intersection of Two Arrays
    Reorder List
    Convert Sorted List to Binary Search Tree
    Remove Duplicates from Sorted List II
    Partition List
    Linked List Cycle II
    Sort List
    struts2结果跳转和参数获取
  • 原文地址:https://www.cnblogs.com/butterflydew/p/9778274.html
Copyright © 2011-2022 走看看