又是一道状压dp...心情复杂.jpg
同样先贴大佬博客:https://blog.csdn.net/u014665013/article/details/70208609
https://blog.csdn.net/libin56842/article/details/24316493 (用栈输出,很巧妙)
有了前几道题的经验,这道题做起来思路上顺多了,但是我还是太菜了,很多地方仍然写不出来55555......
没想到的是pres=st-cur[i]表示之前的作业状态,还有time数组记录之前状态的时间;
另外就是prest、preid数组记录路径,用栈输出数据。
不多说了。。都是泪啊。。。直接上AC代码吧:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
const int INF=0x3f3f3f3f;
int n;
struct subject
{
char s[105];
int dead;
int fini;
}a[17];
int cur[17];
int dp[1<<17];//i(二进制分解后为1的是完成的任务)状态下能减掉最小的分数
int prest[1<<17];//表示当前的状态是由哪一个状态转移过来的
int preid[1<<17];//表示当前的状态是由添加哪一门作业得来的
int time[1<<17];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(cur,0,sizeof(cur));
int tol=1<<n;
for(int i=1;i<=n;i++)
{
scanf("%s%d%d",a[i].s,&a[i].dead,&a[i].fini);
cur[i]+=1<<(i-1);//变成二进制表示选中这个作业
//为了使st=001与作业001对应,因此1<<(i-1)
}
memset(prest,0,sizeof(prest));
memset(preid,0,sizeof(preid));
memset(time,0,sizeof(time));
dp[0]=0;
for(int st=1;st<tol;st++)
{
dp[st]=INF;
for(int i=1;i<=n;i++)
{
if((st&cur[i])==0)//表示第i门作业在状态st下是不是做了,注意括号!!!!!!!
continue;
int pres=st-cur[i];//表示之前的作业状态
int de=time[pres]+a[i].fini-a[i].dead;
if(de<0)
de=0;
//dp[st]=min(dp[st],dp[pres]+de);
if(dp[st]>=dp[pres]+de)//因为按字典序输出,pres中完成作业的序号越靠前越好,所以有"="
{
dp[st]=dp[pres]+de;
prest[st]=pres;
preid[st]=i;
time[st]=time[pres]+a[i].fini;//达到状态st需要的时间
}
}
}
printf("%d\n",dp[tol-1]);
stack<int>s;
int tmp=tol-1;
while(tmp!=0)
{
s.push(preid[tmp]);
tmp=prest[tmp];
}
while(!s.empty())
{
printf("%s\n",a[s.top()].s);
s.pop();
}
}
return 0;
}