求助
查看原帖
求助
373819
lizichang楼主2022/10/25 21:56
#include<bits/stdc++.h>
#include<cstdio>
using namespace std;
int n,q,cnt,f[105][105],head[105];
bool vis[105];
struct node
{
	int u,next,w;
}a[105];
void add(int x,int y,int z)
{
	a[++cnt].u=y;
	a[cnt].w=z;
	a[cnt].next=head[x];
	head[x]=cnt;
}
void dfs(int x)
{
	//cout<<x<<endl;
	bool flag=0;
	int lson,rson;
	for(int i=head[x];i;i=a[i].next)
	{
		if(vis[a[i].u])	continue;
		//cout<<a[i].u<<' ';
		vis[a[i].u]=1;
		if(!flag)	lson=i;
		else rson=i;
		dfs(a[i].u);
		flag=1;
	}
	//cout<<endl;
	f[x][1]=max(a[rson].w,a[lson].w);
	for(int i=1;i<=q;i++)
	{
		for(int j=0;j<=i;j++)
		{
			if(j==0)	f[x][i]=max(f[x][i],f[a[rson].u][i-j-1]+a[rson].w);
			else	f[x][i]=max(f[x][i],f[a[lson].u][j-1]+f[a[rson].u][max(0,i-j-1)]+a[lson].w+(i!=j)*a[rson].w);
		}
	}
}
int main()
{
	int x,y,z;
	cin>>n>>q;
	for(int i=1;i<n;i++)
	{
		cin>>x>>y>>z;
		add(x,y,z);
		add(y,x,z);
	}
	vis[1]=1;
	dfs(1);
	cout<<f[1][q];
	return 0;
}
2022/10/25 21:56
加载中...