zoukankan      html  css  js  c++  java
  • BZOJ4813 CQOI2017小Q的棋盘(树形dp)

      设f[i][j]为由i号点开始在子树内走j步最多能经过多少格点,g[i][j]为由i号点开始在子树内走j步且回到i最多能经过多少格点,转移显然。

    #include<iostream> 
    #include<cstdio>
    #include<cmath>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    #define ll long long
    #define N 110
    char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<'0'||c>'9')) c=getchar();return c;}
    int gcd(int n,int m){return m==0?n:gcd(m,n%m);}
    int read()
    {
        int x=0,f=1;char c=getchar();
        while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
        while (c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
        return x*f;
    }
    int n,m,p[N],f[N][N],g[N][N],t;
    struct data{int to,nxt;
    }edge[N<<1];
    void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;}
    void dfs(int k,int from)
    {
        f[k][0]=g[k][0]=1;for (int i=1;i<=m;i++) f[k][i]=g[k][i]=-n;
        for (int i=p[k];i;i=edge[i].nxt)
        if (edge[i].to!=from)
        {
            dfs(edge[i].to,k);
            for (int x=m;x>=1;x--)
                for (int y=0;y+1<=x;y++)
                f[k][x]=max(f[k][x],max(g[k][x-y-1]+f[edge[i].to][y],(x-y-2>=0?f[k][x-y-2]+g[edge[i].to][y]:-n)));
            for (int x=m;x>=2;x--)
                for (int y=0;y+2<=x;y++)
                g[k][x]=max(g[k][x],g[k][x-y-2]+g[edge[i].to][y]);
        }
        
    }
    int main()
    {
    #ifndef ONLINE_JUDGE
        freopen("bzoj4813.in","r",stdin);
        freopen("bzoj4813.out","w",stdout);
        const char LL[]="%I64d
    ";
    #else
        const char LL[]="%lld
    ";
    #endif
        n=read(),m=read();
        for (int i=1;i<n;i++)
        {
            int x=read()+1,y=read()+1;
            addedge(x,y),addedge(y,x);
        }
        dfs(1,1);
        for (int i=0;i<m;i++) f[1][m]=max(f[1][m],f[1][i]);
        cout<<f[1][m];
        return 0;
    }
  • 相关阅读:
    CORS实践
    xunsearch使用记录
    apk的php解析
    MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT
    企业图谱
    《软件需求工程》阅读笔记03
    2020年下半年学习进度12
    《软件需求工程》阅读笔记02
    2020年下半年学习进度11
    《软件需求工程》阅读笔记01
  • 原文地址:https://www.cnblogs.com/Gloid/p/9972700.html
Copyright © 2011-2022 走看看