[bzoj2097][Usaco2010 Dec]Exercise 奶牛健美操_贪心_树形dp_二分

Exercise bzoj-2097 Usaco-2010 Dec

题目大意题目链接

注释:略。


想法:题目描述生怕你不知道这题在考二分。

关键是怎么验证?我们想到贪心的删边。

这样的策略是显然正确的。

之后树形dp的时候维护一下就行。

最后,附上丑陋的代码... ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 100010
using namespace std;
inline char nc() {static char *p1,*p2,buf[100000]; return (p1==p2)&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;}
int rd() {int x=0; char c=nc(); while(!isdigit(c)) c=nc(); while(isdigit(c)) x=(x<<3)+(x<<1)+(c^48),c=nc(); return x;}
int to[N<<1],nxt[N<<1],head[N],tot;
int cnt,max_dis[N],a[N];
inline void add(int x,int y)
{
    to[++tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
inline bool cmp(int x,int y) {return x>y;}
void dfs(int pos,int fa,int limit)
{
    bool flag=false;
    max_dis[pos]=0;
    for(int i=head[pos];i;i=nxt[i])
    {
        if(to[i]==fa) continue;
        flag=true;
        dfs(to[i],pos,limit);
        max_dis[pos]=max(max_dis[pos],max_dis[to[i]]+1);
    }
    if(!flag) {max_dis[pos]=0; return;}
    a[0]=0;
    for(int i=head[pos];i;i=nxt[i])
    {
        if(to[i]==fa) continue;
        a[++a[0]]=max_dis[to[i]]+1;
    }
    sort(a+1,a+a[0]+1,cmp);
    for(int i=1;i<a[0];i++)
    {
        if(a[i]+a[i+1]>limit) cnt++,a[i]=0;
    }
    if(a[a[0]]>limit) cnt++,a[a[0]]=0;
    sort(a+1,a+a[0]+1,cmp);
    max_dis[pos]=a[1];
}
int n,m;
int calc(int limit)
{
    cnt=0;
    dfs(1,0,limit);
    return cnt;
}
int find()
{
    int l=0,r=n-1,ans=0;
    while(l<=r)
    {
        int mid=(l+r)>>1;
        if(calc(mid)<=m) ans=mid,r=mid-1;
        else l=mid+1;
    }
    return ans;
}
int main()
{
    n=rd(),m=rd();
    int x,y;
    for(int i=1;i<n;i++)
    {
        x=rd(),y=rd();
        add(x,y),add(y,x);
    }
    printf("%d\n",find());
}

小结:有意思...这种题发现直接上东西很艰难,有时候贪心可以适当地在我们的考虑范围之内。

posted @   JZYshuraK_彧  阅读(131)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示