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\n",L);
54     return 0;
55 }
View Code

 

posted @ 2017-09-11 16:56  Blue233333  阅读(208)  评论(0编辑  收藏  举报