HDU 1074 动态规划

HDU 1074

慢慢写了半个多小时的dp,思路很清楚,二进制保存状态,然后如果这个状态为0,就添上1转移,并且记录路径,做之前一定要想好要记录哪些东西,由于一个状态不管cost是啥,总之是一样的。因为不管什么状态,加到这一步,总天数都是一样的。

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int vis[1<<15+5];
struct Work
{
    char name[110];
    int deadline;
    int cost;
}date[20];

struct Go
{
    int pre;
    int reduce;
    int cost;
}dp[1<<15+5];

void out(int temp)
{
    int tempnext=dp[temp].pre;
    if (tempnext!=-1)
    {
        int a=(int)(log(temp-tempnext)/log(2));
        out(tempnext);
        printf ("%s\n",date[a].name);
    }
    else return;
}

int main()
{
    int T,n;
    scanf ("%d",&T);
    while(T--)
    {
        scanf ("%d",&n);
        memset(vis,0,sizeof(vis));
        memset(dp,0,sizeof(dp));
        for (int i=0;i<n;i++)
        {
            scanf ("%s%d%d",date[i].name,&date[i].deadline,&date[i].cost);
        }
        int maxdp=(1<<n)-1;
        dp[0].pre=-1;
        dp[0].reduce=0;
        dp[0].cost=0;
        for (int i=0;i<maxdp;i++)
        {
            for (int j=0;j<n;j++)
            {
                int cur=1<<j;
                if ((i&cur)==0)
                {
                    int curnext=cur|i;
                    int day=dp[i].cost+date[j].cost;
                    dp[curnext].cost=day;
                    int rreduce=day-date[j].deadline;
                    if (rreduce<=0) rreduce=0;
                    rreduce+=dp[i].reduce;
                    if (vis[curnext])
                    {
                        if (rreduce<dp[curnext].reduce)
                        {
                            dp[curnext].reduce=rreduce;
                            dp[curnext].pre=i;
                        }
                    }
                    else
                    {
                        vis[curnext]=1;
                        dp[curnext].pre=i;
                        dp[curnext].reduce=rreduce;
                    }
                }
            }
        }
        printf ("%d\n",dp[maxdp].reduce);
        out(maxdp);
    }
    return 0;
}

posted on 2016-04-13 14:05  very_czy  阅读(155)  评论(0编辑  收藏  举报

导航