题意:
是找到和给出的分钟数相加最长的,但不长于所给的分钟数N。
思路:
01背包,加路径跟踪。
#include <iostream> #include <cstring> #include <cstdio> using namespace std; int N,tracksNum,tracks[22]; int bags[50030]; bool visit[50030][22]; void init(); void compu(); void output(); int main() { #ifndef ONLINE_JUDGE freopen("D:\acm.txt","r",stdin); #endif // ONLINE_JUDGE compu(); return 0; } void init(){ memset(bags,0,sizeof(bags)); memset(tracks,0,sizeof(tracks)); memset(visit,false,sizeof(visit)); } void output(){ for(int i = tracksNum - 1,j = N;i >= 0;i--){//输出路径 if(visit[j][i]){ cout << tracks[i]<<" "; j = j - tracks[i]; } } cout<<"sum:"<<bags[N]<<endl; } void compu(){ while(cin >> N){ init(); cin>>tracksNum; for(int i = 0;i < tracksNum;i++) cin>>tracks[i]; ///////////////////////////////////////// for(int i = 0;i < tracksNum;i++){ for(int j = N;j >= tracks[i];j--){ if(bags[j] < bags[j - tracks[i]] + tracks[i]){ bags[j] = bags[j - tracks[i]] + tracks[i]; visit[j][i] = true; } } } //////////////////// output(); } }