二叉苹果树--树上动态规划

二叉苹果树--树上动态规划

 

 

#include<cstring>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define maxn 200
using namespace std;
int val[maxn];
struct Node {
	int p;
	int len;
	Node(int a, int b) :p(a), len(b) {}
};
vector<Node>G[maxn];
void insert(int be, int en,int len) {
	G[be].push_back(Node(en, len));
}
int n, m;
int l[maxn], r[maxn];
int dfs1(int x,int fa) {//建立树
	for (int i = 0; i < G[x].size(); i++) {
		int p = G[x][i].p;
		if (p == fa) continue;
		val[p] = G[x][i].len;
		if (!l[x]) l[x] = p;
		else r[x] = p;
		dfs1(p, x);
	}
	return 0;
}
int dp[maxn][maxn];
int dfs(int i, int j) {//编号i,有j个树枝
	if (j == 0) return 0;
	if (l[i] == 0 && r[i] == 0) return val[i];
	if (dp[i][j] > 0) return dp[i][j];

	for (int k = 0; k < j; k++) {
		dp[i][j] = max(dp[i][j], dfs(l[i], k) + dfs(r[i], j - k - 1) + val[i]);
	}
	return dp[i][j];
}
int main() {
	memset(dp, -1, sizeof(dp));
	int be, en, len;
	scanf("%d %d", &n, &m);
	m++;
	for (int i = 0; i < n-1; i++) {
		scanf("%d %d %d", &be, &en, &len);
		insert(be, en, len);
		insert(en, be, len);
	}
	dfs1(1, -1);
	int chal = dfs(1, m);
	cout << chal << endl;
	return 0;
}

  

 

二叉苹果树--树上动态规划

上一篇:Android_基于监听的事件处理机制


下一篇:WhatsApp被曝漏洞:一张GIF动图黑客便可接管账户