來源:http://acm.hdu.edu.cn/showproblem.php?pid=1074
參考了網上的代碼,然後自己又重新敲了一遍。
需要用到狀態壓縮,壓成二進制來表示不同的狀態。有關狀態壓縮的講解:http://www.cnblogs.com/avril/archive/2013/08/26/3282295.html
幾點要點:
1.如果不用狀態壓縮,直接窮舉,最多會有15!種狀態,肯定會超時。用二進制只需15位,每位表示一門課程,最多隻有2^15種狀態,這複雜度完全可以接受。
2.我們用0和1來判斷課程是否被完成。
3.dp的過程由i-1位推出i位。例如15=1111,可以由11=1011,13=1101,14=1110,7=0111來得到,只需要判斷從這4個狀態中哪個狀態獲得的分數最低,便
確定了sta[15]。直到確定最後的sta[n<<1-1]。
#include<stdio.h>
#include<string>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
struct subject//課程
{
char name[101];
int day,core;
};
struct state
{
int prestate;//前一個狀態
int nowsubject;//從前一狀態到當前狀態完成的課程
int uesdtime;//到這一狀態花費的時間
int cost;//到這一狀態減少的分數
};
int n;//課程數
subject sub[16];
state sta[1<<15];//1<<15=2^15,可能的狀態總數
void DP()
{
int prestate,i,j,k,j1,cost;
sta[0].prestate=-1;sta[0].nowsubject=0;sta[0].uesdtime=0;sta[0].cost=0;//初始化
k=1<<n;
for(i=1;i<k;i++)
{
sta[i].cost=0x7fffffff;
for(j=n-1;j>=0;j--)//從後面的課程開始往前遍歷,爲了滿足當減少的分數一致,按課程字母順序遞增的方式排列
{
j1=1<<j;
if(i&j1)//i狀態含有j課程
{
prestate=i-j1;
cost=sta[prestate].uesdtime+sub[j].core-sub[j].day;
if(cost<0)cost=0;
if(sta[prestate].cost+cost<sta[i].cost)//篩選出最小分數
{
sta[i].prestate=prestate;
sta[i].nowsubject=j;
sta[i].cost=sta[prestate].cost+cost;
sta[i].uesdtime=sta[prestate].uesdtime+sub[j].core;
}
}
}
}
}
void print()//利用棧輸出課程,因爲我們只能確定結束的狀態。
{
int k,prestate,nowsubject,i;
stack<int> s;
k=1<<n;
printf("%d\n",sta[k-1].cost);
k=k-1;
while(k)
{
prestate=sta[k].prestate;
nowsubject=sta[k].nowsubject;
k=prestate;
s.push(nowsubject);
}
while(!s.empty())
{
i=s.top();s.pop();
printf("%s\n",sub[i].name);
}
}
int main()
{
int t,i;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%s%d%d",sub[i].name,&sub[i].day,&sub[i].core);
DP();
print();
}
return 0;
}