• BZOJ2097: [Usaco2010 Dec]Exercise 奶牛健美操


    n<=100000的树,砍S<n条边,求砍完后S+1棵树的最大直径的最小值。

    树的直径要小小哒,那考虑一棵子树的情况吧!一棵子树的直径,就是子树根节点各儿子的最大深度+次大深度。就下面这样:

    最大值最小肯定二分答案啦,那这棵子树如果有毛病呢,砍谁呢?肯定砍最大深度啦!所以就子树最大深度+次大深度有毛病就砍最大,没毛病把最大传上去。

    写的优先队列,感觉排序会快一点??

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 #include<algorithm>
     5 #include<queue>
     6 //#include<iostream>
     7 using namespace std;
     8 
     9 int n,S;
    10 #define maxn 200011
    11 struct Edge{int to,next;}edge[maxn];int first[maxn],le=2;
    12 void in(int x,int y) {Edge &e=edge[le];e.to=y;e.next=first[x];first[x]=le++;}
    13 void insert(int x,int y) {in(x,y);in(y,x);}
    14 int lim,cnt;
    15 int dfs(int x,int fa)
    16 {
    17     priority_queue<int> q;
    18     for (int i=first[x];i;i=edge[i].next)
    19     {
    20         const Edge &e=edge[i];if (e.to==fa) continue;
    21         q.push(dfs(e.to,x));
    22     }
    23     while (!q.empty())
    24     {
    25         const int now=q.top();q.pop();
    26         if (!q.empty())
    27         {
    28             if (q.top()+now<=lim) {q.push(now);break;}
    29             cnt++;
    30         }
    31         else if (now<=lim) {q.push(now);break;}
    32         else cnt++;
    33     }
    34     return q.empty()?1:q.top()+1;
    35 }
    36 int x,y;
    37 int main()
    38 {
    39     scanf("%d%d",&n,&S);
    40     for (int i=1;i<n;i++)
    41     {
    42         scanf("%d%d",&x,&y);
    43         insert(x,y);
    44     }
    45     int L=1,R=n;
    46     while (L<R)
    47     {
    48         const int mid=(L+R)>>1;
    49         lim=mid,cnt=0;dfs(1,0);
    50         if (cnt<=S) R=mid;
    51         else L=mid+1;
    52     }
    53     printf("%d
    ",L);
    54     return 0;
    55 }
    View Code
  • 相关阅读:
    排序算法之希尔排序
    排序算法之直接插入排序
    PL/SQL之异常
    PL/SQL之包
    PL/SQL之存储过程和函数
    Oracle左连接、右连接、全外连接以及(+)号用法
    PL/SQL之存储过程和触发器实例
    PL/SQL之游标的使用
    Tag Tree
    目录:JAVA
  • 原文地址:https://www.cnblogs.com/Blue233333/p/7505771.html
Copyright © 2020-2023  润新知