BZOJ4813 CQOI2017小Q的棋盤(樹形dp)
阿新 • • 發佈:2018-11-17
bzoj online truct color 轉移 struct con div ons
設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 (inti=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\n"; #else const char LL[]="%lld\n"; #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; }
BZOJ4813 CQOI2017小Q的棋盤(樹形dp)