bzoj 4813: [Cqoi2017]小Q的棋盘 [树形背包dp]

4813: [Cqoi2017]小Q的棋盘

题意:


某poj弱化版?树形背包

据说还可以贪心...

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 105;
inline int read() {
    char c=getchar(); int x=0,f=1;
    while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
    while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
    return x*f;
}

int n, m;
struct edge{int v, ne;} e[N<<1];
int cnt, h[N];
inline void ins(int u, int v) {
	e[++cnt] = (edge){v, h[u]}; h[u] = cnt;
	e[++cnt] = (edge){u, h[v]}; h[v] = cnt;
}
int f[N][N][2];
void dfs(int u, int fa) {
	for(int i=0; i<=m; i++) f[u][i][0] = f[u][i][1] = 1;
	for(int i=h[u]; i; i=e[i].ne) {
		int v = e[i].v;
		if(v == fa) continue;
		dfs(v, u);
		for(int j=m; j>=0; j--)
			for(int k=1; k<=j; k++) {
				if(k >= 1) f[u][j][0] = max(f[u][j][0], f[u][j-k][1] + f[v][k-1][0]);
				if(k >= 2) {
					f[u][j][1] = max(f[u][j][1], f[u][j-k][1] + f[v][k-2][1]);
					f[u][j][0] = max(f[u][j][0], f[u][j-k][0] + f[v][k-2][1]);
				}
			}
	}
}

int main() {
	freopen("in", "r", stdin);
	n=read(); m=read();
	for(int i=1; i<n; i++) ins(read()+1, read()+1);
	dfs(1, 0);
	printf("%d\n", f[1][m][0]);
}

posted @ 2017-04-25 13:51  Candy?  阅读(272)  评论(0编辑  收藏  举报