您的位置:首页 > 其它

蓝桥杯 算法提高 金属采集 (树形动态规划)

2014-07-15 16:38 211 查看
//  蓝桥杯 算法提高 金属采集 (树形动态规划)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int N=100010;
const int M=12;
struct Node
{
int child;
int value;
}s;
int visit
={0};//判断是否遍历的节点
int dp
[M]={0};
int cost
={0};
int n,dir,m;//n节点数,dir位置,m机器人数
vector<Node> no
;
int Min(int a,int b)
{
if(a<b)
{
return a;
}
return b;
}
void pr()
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
}
void DP(int root)//把子的状态都移到父的状态
{
int i;
for(i=0;i<=m;i++)
{
dp[root][i]=0;
}
visit[root]=1;
for(i=0;i<no[root].size();i++)
{
int son=no[root][i].child;
if(visit[son]) continue;
DP(son);
cost[son]=no[root][i].value;
for(int mi=m;mi>=0;mi--)//节点拥有的火星数
{
dp[root][mi]+=dp[son][0]+cost[son]*2;
for(int mj=1;mj<=mi;mj++)//进行动态的转移
{
dp[root][mi]=Min(dp[root][mi],dp[root][mi-mj]+mj*cost[son]+dp[son][mj]);
}
}
}
}
int main()
{
scanf("%d%d%d",&n,&dir,&m);
int a1,a2,dis;
while(scanf("%d%d%d",&a1,&a2,&dis)==3)
{
s.child=a1;
s.value=dis;
no[a2].push_back(s);
s.child=a2;
s.value=dis;
no[a1].push_back(s);
}
DP(dir);
printf("%d\n",dp[dir][m]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: