You have a long drive by car ahead. You have a tape recorder, but unfortunately your best music is on CDs. You need to have it on tapes so the problem to solve is: you have a tape N minutes long. How to choose tracks from CD to get most out of tape space and have as short unused space as possible.
Assumptions:
- number of tracks on the CD. does not exceed 20
- no track is longer than N minutes
- tracks do not repeat
- length of each track is expressed as an integer number
- N is also integer
Program should find the set of tracks which fills the tape best and print it in the same sequence as the tracks are stored on the CD
5 3 1 3 4 10 4 9 8 4 2 20 4 10 5 7 4 90 8 10 23 1 2 3 4 5 7 45 8 4 10 44 43 12 9 8 2
1 4 sum:5 8 2 sum:10 10 5 4 sum:19 10 23 1 2 3 4 5 7 sum:55 4 10 12 9 8 2 sum:45
01背包问题。使用vector容器来解决这个问题,这样会变得很简单。然后就是套01背包模板。
#include<iostream>
#include<vector>
#define M 0x3f3f3f3f
using namespace std;
int main()
{
int n,m,x,sum;
vector<int>v[10005];
while(cin>>n>>m)
{
sum=0;
for(int i=1; i<=n; i++)
{
v[i].clear();
}
for(int i=1; i<=m; i++)
{
cin>>x;
sum+=x;
for(int i=sum; i>=0; i--)
{
if((i==0||v[i].size()!=0)&&v[i+x].size()==0)//判断是否出现过
{
for(int j=0; j<v[i].size(); j++)
{
v[i+x].push_back(v[i][j]);
}
v[i+x].push_back(x);
}
}
}
int i=n;
for(;i>=0;i--)
{
if(v[i].size())
break;
}
for(int j=0;j<v[i].size();j++)
cout<<v[i][j]<<" ";
cout<<"sum:"<<i<<endl;
}
}