【树形DP】 HDOJ 5148 Cities

对于每个节点枚举子节点即可。。。

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 2005
#define maxm 4005
#define eps 1e-10
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
// head

struct Edge
{
	int v, c;
	Edge *next;
}*H[maxn], E[maxm], *edges;

LL dp[2005][105];
int vis[maxn];
int n, k;
LL ans;

void addedges(int u, int v, int c)
{
	edges->v = v;
	edges->c = c;
	edges->next = H[u];
	H[u] = edges++;
}

void init(void)
{
	edges = E;
	memset(H, 0, sizeof H);
	memset(dp, -1, sizeof dp);
	memset(vis, 0, sizeof vis);
}

void read(void)
{
	int a, b, c;
	scanf("%d%d", &n, &k);
	for(int i = 1; i < n; i++) {
		scanf("%d%d%d", &a, &b, &c);
		addedges(a, b, c);
		addedges(b, a, c);
	}
}

void dfs(int u)
{
	dp[u][1] = 0;
	for(Edge *e = H[u]; e; e = e->next) {
		if(!vis[e->v]) {
			vis[e->v] = 1;
			dfs(e->v);
			for(int i = k-1; i >= 0; i--)
				if(dp[u][i] != -1)
					for(int j = 1; j < k; j++)
						if(dp[e->v][j] != -1) {
							int w = 2 * j * (k - j) * e->c;
							if(dp[u][i + j] == -1) dp[u][i + j] = dp[u][i] + dp[e->v][j] + w;
							else dp[u][i + j] = min(dp[u][i + j], dp[u][i] + dp[e->v][j] + w);
						}
		}
	}
	if(dp[u][k] != -1) ans = min(dp[u][k], ans);
}

void work(void)
{
	if(k == 1) {
		printf("0\n");
		return;
	}
	ans = 1e17;
	vis[1] = 1;
	dfs(1);
	printf("%I64d\n", ans);
}

int main(void)
{
	int _;
	while(scanf("%d", &_)!=EOF) {
		while(_--) {
			init();
			read();
			work();
		}
	}

	return 0;
}


你可能感兴趣的:(HDU)