题目链接:点击打开链接
dp+状态压缩的题。
代码:
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<map>
#include<vector>
#include<iomanip>
#include<queue>
using namespace std;
const int N=1<<16;
struct Node {
int time,dt;
string name;
} sub[16];
struct S {
int time,cost,status;
char s[17];
} dp[N];
int n;
void bfs() {
queue<S> que;
S ss;
ss.time=ss.cost=ss.status=0;
ss.s[0]='\0';
dp[0]=ss;
que.push(ss);
while(!que.empty()) {
ss=que.front();
que.pop();
for(int i=0; i<n; ++i) {
S ts;
if((ss.status&(1<<i))!=0) continue;
//没有含第i门课程
ts.status=ss.status|(1<<i);
ts.time=ss.time+sub[i].time;
ts.cost=ss.cost;
if(ts.time>sub[i].dt)
ts.cost+=ts.time-sub[i].dt;
if(dp[ts.status].cost==-1||ts.cost<dp[ts.status].cost) {
strcpy(ts.s,ss.s);
int len=strlen(ts.s);
ts.s[len]='0'+i;
ts.s[len+1]='\0';
dp[ts.status]=ts;
que.push(ts);
}
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int T;
cin>>T;
while(T--) {
cin>>n;
for(int i=0; i<n; ++i) {
cin>>sub[i].name>>sub[i].dt>>sub[i].time;
}
memset(dp,0,sizeof(dp));
for(int i=0; i<1<<n; ++i)
dp[i].cost=-1;
bfs();
int l=(1<<n)-1;
cout<<dp[l].cost<<endl;
for(int i=0; i<n; ++i) {
cout<<sub[dp[l].s[i]-'0'].name<<endl;
}
}
return 0;
}
附加一个带有很奇怪错误的代码:其中换成string类型了,就错误了,哪位高人指点下哈!
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<map>
#include<vector>
#include<iomanip>
#include<queue>
using namespace std;
const int N=1<<16;
struct Node {
int time,dt;
string name;
} sub[16];
struct S {
int time,cost,status;
string s;
} dp[N];
int n;
void bfs() {
queue<S> que;
S ss;
ss.time=ss.cost=ss.status=0;
dp[0]=ss;
que.push(ss);
while(!que.empty()) {
ss=que.front();
que.pop();
for(int i=0; i<n; ++i) {
S ts;
if((ss.status&(1<<i))!=0) continue;
//没有含第i门课程
ts.status=ss.status|(1<<i);
ts.time=ss.time+sub[i].time;
ts.cost=ss.cost;
if(ts.time>sub[i].dt)
ts.cost+=ts.time-sub[i].dt;
if(dp[ts.status].cost==-1||ts.cost<dp[ts.status].cost) {
ts.s=ss.s;
ts.s.push_back('0'+i);
dp[ts.status]=ts;
que.push(ts);
}
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int T;
cin>>T;
while(T--) {
cin>>n;
for(int i=0; i<n; ++i) {
cin>>sub[i].name>>sub[i].dt>>sub[i].time;
}
memset(dp,0,sizeof(dp));
for(int i=0; i<1<<n; ++i)
dp[i].cost=-1;
bfs();
int l=(1<<n)-1;
cout<<dp[l].cost<<endl;
for(int i=0; i<n; ++i) {
cout<<sub[dp[l].s[i]-'0'].name<<endl;
}
}
return 0;
}