HDU1074
题意就是有n个科目要掌握,每种科目有一个开始时间和持续时间,求最少需要的时间
由于这个题n比较小,就是经典的状压DP,我们可以从小到大枚举所有状态,然后对每种状态保留能达到当前状态的最优解,再从小状态向大状态转移。由于这道题要输出保证字典序而且原题就是按照字典序给出的,所以我们可以倒着遍历,这样就保证了字典序。
HDU1074代码
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn = 17;
struct data
{
char str[105];
int d;
int w;
}x[15];
struct data2
{
int time,pre,cost,en;
}dp[1<<maxn];
int ans[maxn];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s%d%d",x[i].str,&x[i].d,&x[i].w);
}
int all=(1<<n)-1;
for(int i=0;i<=all;i++)
{
dp[i].time=0;
dp[i].pre=0;
dp[i].en=0;
dp[i].cost=INF;
}
dp[0].cost=0;
for(int i=1;i<=all;i++)
{
for(int j=n-1;j>=0;j--)//为了字典序。
{
if(i&(1<<j))
{
int tmp=i-(1<<j);
int pp=max(0,dp[tmp].time+x[j].w-x[j].d);
if(pp+dp[tmp].cost<dp[i].cost)
{
dp[i].time=dp[tmp].time+x[j].w;
dp[i].pre=tmp;
dp[i].en=j;
dp[i].cost=pp+dp[tmp].cost;
}
}
}
}
int cnt=0;
int tmp=all;
while(tmp)
{
ans[cnt++]=dp[tmp].en;
tmp=dp[tmp].pre;
}
printf("%d\n",dp[all].cost);
for(int i=cnt-1;i>=0;i--)
{
printf("%s\n",x[ans[i]].str);
}
}
return 0;
}