HDU 1074 Doing Homework(状压DP)

题目地址:HDU 1074

这题攒了好长时间了。。。一直没写。。

简单状压DP。这题比較特别的地方是dp须要用结构体数组。

具体的请看kuangbin大神的模板。。传送门

代码例如以下:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
#define LL __int64
const int INF=0x3f3f3f3f;
struct node1
{
    char s[110];
    int d, c;
}fei[20];
struct node2
{
    int d, p, pre, t;
}dp[1<<16];
void output(int x)
{
    if(dp[x].pre==-1) return ;
    output(dp[x].pre);
    printf("%s
",fei[dp[x].t].s);
}
int main()
{
    int t, n, i, j, x, y, ans, tmp, k;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            getchar();
            scanf("%s%d%d",fei[i].s,&fei[i].d,&fei[i].c);
        }
        k=1<<n;
        dp[k-1].d=0;
        dp[k-1].p=0;
        dp[k-1].pre=-1;
        for(i=k-2;i>=0;i--)
        {
            dp[i].p=INF;
        }
        for(i=k-1;i>=0;i--)
        {
            for(j=0;j<n;j++)
            {
                if(i&(1<<j))
                {
                    tmp=i-(1<<j);
                    x=dp[i].d+fei[j].c;
                    y=dp[i].p;
                    if(x>fei[j].d)
                        y=dp[i].p+x-fei[j].d;
                    if(dp[tmp].p>y)
                    {
                        dp[tmp].p=y;
                        dp[tmp].t=j;
                        dp[tmp].d=x;
                        dp[tmp].pre=i;
                    }
                }
            }
        }
        printf("%d
",dp[0].p);
        output(0);
    }
    return 0;
}


原文地址:https://www.cnblogs.com/lxjshuju/p/7048616.html