首页 > 代码库 > [luoguP1272] 重建道路

[luoguP1272] 重建道路

传送门

 

奇奇怪怪的分组背包。

 

#include <cstdio>#include <cstring>#include <iostream>#define N 151#define min(x, y) ((x) < (y) ? (x) : (y))int n, p, cnt, ans = ~(1 << 31);int head[N], to[N], next[N], f[N][N];inline int read(){	int x = 0, f = 1;	char ch = getchar();	for(; !isdigit(ch); ch = getchar()) if(ch == ‘-‘) f = -1;	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - ‘0‘;	return x * f;}inline void dfs(int u){	int i, j, k, v;	for(i = head[u]; i ^ -1; i = next[i])	{		v = to[i];		dfs(v);		for(j = p; j >= 1; j--)			for(k = 1; k < j; k++)				f[u][j] = min(f[u][j], f[u][j - k] + f[v][k] - 2);	}}inline void add(int x, int y){	to[cnt] = y;	next[cnt] = head[x];	head[x] = cnt++;}int main(){	int i, x, y;	n = read();	p = read();	memset(f, 127 / 3, sizeof(f));	memset(head, -1, sizeof(head));	for(i = 1; i <= n; i++) f[i][0] = f[i][1] = 0;	for(i = 1; i < n; i++)	{		x = read();		y = read();		add(x, y);		f[x][1]++;		f[y][1]++;	}	dfs(1);	for(i = 1; i <= n; i++) ans = min(ans, f[i][p]);	printf("%d\n", ans);	return 0;}

  

[luoguP1272] 重建道路