题目链接点击打开链接
题意:现在有n个作业,每个作业有其名称、耗时、提交期限。超过提交期限一天扣1分。问怎么排序能使扣的分数最少。(n<=15)
思路:一道入门的状态压缩dp。看到n<=15,基本上就是个状态压缩dp了。
AC代码
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int N = 1<<17;
const int inf = 1<<25;
struct node
{
int c,d;
char name[20];
}a[N];
struct p
{
int score,ed,pre,now;
}dp[N];
void init()
{
for(int i=0;i<N;i++) dp[i].score = inf,dp[i].ed = 0;
dp[0].score = 0;
}
int main()
{
int n,m,T;
scanf("%d",&T);
while(T--)
{
init();
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%s %d%d",&a[i].name,&a[i].d,&a[i].c);
int ed = (1<<n);
for(int i=0;i<ed;i++)
{
for(int j = n-1;j>=0;j--)
{
if(i & (1<<j))
{
int last = i-(1<<j);
int t =dp[last].ed + a[j].c - a[j].d ;
t = max(t,0);
if(dp[last].score+t<dp[i].score)
{
dp[i].score = dp[last].score + t;
dp[i].pre = last;
dp[i].now = j ;
dp[i].ed = dp[last].ed + a[j].c;
}
}
}
}
stack< int > s;
printf("%d\n",dp[ed-1].score);
int t = ed-1;
while(t!=0)
{
s.push(dp[t].now) ;
t = dp[t].pre;
}
while(!s.empty())
{
int id = s.top();
s.pop();
printf("%s\n",a[id].name);
}
}
return 0;
}