zoukankan      html  css  js  c++  java
  • 【bzoj2060/Usaco2010 Nov】Visiting Cows 拜访奶牛——树形dp

    Description

    经过了几周的辛苦工作,贝茜终于迎来了一个假期.作为奶牛群中最会社交的牛,她希望去拜访N(1<=N<=50000)个朋友.这些朋友被标号为1..N.这些奶牛有一个不同寻常的交通系统,里面有N-1条路,每条路连接了一对编号为C1和C2的奶牛(1 <= C1 <= N; 1 <= C2 <= N; C1<>C2).这样,在每一对奶牛之间都有一条唯一的通路. FJ希望贝茜尽快的回到农场.于是,他就指示贝茜,如果对于一条路直接相连的两个奶牛,贝茜只能拜访其中的一个.当然,贝茜希望她的假期越长越好,所以她想知道她可以拜访的奶牛的最大数目.

    Input

    第1行:单独的一个整数N 第2..N行:每一行两个整数,代表了一条路的C1和C2.

    Output

    单独的一个整数,代表了贝茜可以拜访的奶牛的最大数目.

    Sample Input

    7
    6 2
    3 4
    2 3
    1 2
    7 6
    5 6


    INPUT DETAILS:

    Bessie knows 7 cows. Cows 6 and 2 are directly connected by a road,
    as are cows 3 and 4, cows 2 and 3, etc. The illustration below depicts the
    roads that connect the cows:

    1--2--3--4
         |
    5--6--7


    Sample Output

    4
     

    类似于没有上司的舞会,f[i][0]表示不拜访i的最大值,f[i][1]则表示拜访i。然后随便找一个点为根瞎dp一下就好了。
    代码:
     1 #include<cstdio>
     2 #include<cstring>
     3 #include<algorithm>
     4 const int N=5e4+10;
     5 using std::max;
     6 struct node{int ne,to;}e[N*2];
     7 int n,tot=0,first[N];
     8 int read(){
     9     int ans=0,f=1;char c=getchar();
    10     while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    11     while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
    12     return ans*f;
    13 }
    14 int f[N][2];
    15 void ins(int u,int v){e[++tot]=(node){first[u],v};first[u]=tot;}
    16 void dfs(int x,int fa){
    17     f[x][1]=1;
    18     for(int i=first[x];i;i=e[i].ne){
    19         int to=e[i].to;
    20         if(to==fa)continue;
    21         dfs(to,x);f[x][0]+=max(f[to][0],f[to][1]);f[x][1]+=f[to][0];
    22     }
    23 }
    24 int main(){
    25     n=read();
    26     for(int i=1,a,b;i<n;i++)a=read(),b=read(),ins(a,b),ins(b,a);
    27     dfs(1,0);
    28     printf("%d",max(f[1][0],f[1][1]));
    29     return 0;
    30 }
    31 
    bzoj2060
  • 相关阅读:
    js将手机号中间四位变成*
    js判断浏览器客户端类型
    vue项目涉及到的setInterval
    MYSQL 总结——2
    MySQL补充
    PyCharm软件安装
    MYSQL 总结——1
    linux系统通过ssh拉取gitee项目 设置权限
    tp5开源的后台管理系统
    window下Python安装
  • 原文地址:https://www.cnblogs.com/JKAI/p/7663236.html
Copyright © 2011-2022 走看看