HDU - 1074 Doing Homework 状态压缩dp

Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test, 1 day for 1 point. And as you know, doing homework always takes a long time. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=15) which indicate the number of homework. Then N lines follow. Each line contains a string S(the subject's name, each string will at most has 100 characters) and two integers D(the deadline of the subject), C(how many days will it take Ignatius to finish this subject's homework).

Note: All the subject names are given in the alphabet increasing order. So you may process the problem much easier.

Output

For each test case, you should output the smallest total reduced score, then give out the order of the subjects, one subject in a line. If there are more than one orders, you should output the alphabet smallest one.

Sample Input

2
3
Computer 3 3
English 20 1
Math 3 2
3
Computer 3 3
English 6 3
Math 6 3

Sample Output

2
Computer
Math
English
3
Computer
English
Math

思路:

这道题一开始爆搜了一下,tle了,然后上网上搜了下题解,才知道用的是状态压缩dp。

在这里附上别人的题解:

传送门

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=20;
int q,n;
int dead[maxn];
int need[maxn];
char name[maxn][105];
int dp[1<<15];
int day[1<<15];
int pre[1<<15];
void output (int x)
{
    if(x==0) return;
    output(x^(1<<pre[x]));
    printf("%s\n",name[pre[x]]);
}
int main()
{
    scanf("%d",&q);
    while (q--)
    {
        scanf("%d",&n);
        int bits=1<<n;
        memset (day,0,sizeof(day));
        memset (pre,0,sizeof(pre));
        for (int i=0;i<n;i++)
        {
            scanf("%s%d%d",name[i],&dead[i],&need[i]);
        }
        for (int i=1;i<bits;i++)
        {
            dp[i]=0x3f3f3f3f;
            for (int j=n-1;j>=0;j--)
            {
                int t=1<<j;
                if((t&i)==0) continue;
                int tt=t^i;
                int time=day[tt]+need[j];
                int lose=0;
                if(time>dead[j]) lose=time-dead[j];
                if(dp[i]>dp[tt]+lose)
                {
                    dp[i]=dp[tt]+lose;
                    day[i]=time;
                    pre[i]=j;
                }
            }
        }
        printf("%d\n",dp[bits-1]);
        output(bits-1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/87813046