您的位置:首页 > 其它

hdu 1074

2014-07-23 08:57 232 查看
又是状态压缩的dp。

要输出路径,那只要记录每个状态的前一个状态,就能那样递归输出了。

贴代码。

#include<iostream>
#include<string>
#include<stack>
using namespace std;
struct node{
string name;
int d;                                  //截止日期
int c;                                  //需要花费日期
}hw[20];

struct point{
int now,pre;                           //当前状态id,与过去状态id
int now_time;                          //当前时间
int score;                             //当前最少花费
int key;                               //当前课程的id

}dp[40000];
int main(){
int t,n,i,j;

cin>>t;

while(t--){
cin>>n;
for(i=0;i<n;i++)  cin>>hw[i].name>>hw[i].d>>hw[i].c;

dp[0].now_time=0;  dp[0].score=0;   dp[0].now=0;

for(i=1;i<(1<<(n));i++){
dp[i].score=1000000000;
for(j=n-1;j>=0;j--){
if(i&(1<<j)){
int pre_id=i-(1<<j),temp=0;

if(dp[pre_id].now_time+hw[j].c>hw[j].d)
temp=dp[pre_id].now_time+hw[j].c-hw[j].d;
else temp=0;

if(dp[pre_id].score+temp<dp[i].score){
dp[i].score=dp[pre_id].score+temp;
dp[i].now=i;
dp[i].pre=pre_id;
dp[i].now_time = dp[pre_id].now_time+hw[j].c;
dp[i].key=j;

}
}
}

}

stack<string >st;
cout<<dp[(1<<n)-1].score<<endl;

int t=(1<<(n))-1;

while(dp[t].now!=0){

st.push(hw[dp[t].key].name);
t=dp[t].pre;
//  cout<<t<<endl;

}
while(!st.empty()){
cout<<st.top()<<endl;
st.pop();
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: