HDU-4003-树形dp

来源:互联网 发布:pdz文件阅读器 mac 编辑:程序博客网 时间:2024/05/20 20:47

题目大意:给定一个n个节点的树和初始节点s,在初始节点上有k个机器人,现在要使得所有机器人遍历所有边,问最小花费是多少;

题目解析:首先考虑如果只有一个机器人并且需要最后返回原点,那么一共需要花费2*sum的值,定义dp[i][j]为在i上安排j个机器人可以减少的最多花费,那么答案就是2*sum-dp[s][k],现在假设在第u个节点上,v为它的儿子,如果v上安排了x个,那么最终答案会减少(2-x)乘以这条边的cost;

AC代码:

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<string>using namespace std;const int inf=0x3fffffff;const int maxn=10010;int tot,head[maxn],n,m,dp[maxn][12];bool vis[maxn];struct Edge{        int to,next,w;}edge[maxn<<1];void init(){        memset(head,-1,sizeof(head));        tot=0;}void addedge(int u,int v,int cost){        edge[tot].to=v;        edge[tot].next=head[u];        edge[tot].w=cost;        head[u]=tot++;}void dfs(int root){        vis[root]=1;        for(int i=head[root];i!=-1;i=edge[i].next)        {                int v=edge[i].to;                int cost=edge[i].w;                if(vis[v])       continue;                dfs(v);                for(int j=m;j>=1;j--)                {                       for(int k=0;k<j;k++)                       {                               dp[root][j]=max(dp[root][j],dp[root][k]+dp[v][j-k]+(2-j+k)*cost);                       }                }        }}int main(){        int s,sum;        while(scanf("%d%d%d",&n,&s,&m)!=EOF)        {                init();                memset(vis,0,sizeof(vis));                memset(dp,0,sizeof(dp));                sum=0;                for(int i=1;i<n;i++)                {                        int u,v,w;                        scanf("%d%d%d",&u,&v,&w);                        addedge(u,v,w);                        addedge(v,u,w);                        sum+=w;                }                dfs(s);                int ans=dp[s][m];                printf("%d\n",2*sum-ans);        }        return 0;}



0 0