CD |
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.html
Assumptions:ios
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 CDexpress
Any number of lines. Each one contains value N, (after space) number of tracks and durations of the tracks. For example from first line in sample data: N=5, number of tracks=3, first track lasts for 1 minute, second one 3 minutes, next one 4 minutes數組
Set of tracks (and durations) which are the correct solutions and string ``sum:" and sum of duration times.ide
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
給出一些歌曲的時長,給出一個時長爲N的磁帶,將這些歌曲中的一部分錄制到磁帶上,求最長能夠錄多長時間的歌(即便磁帶的利用率最高),並列出所錄的歌曲。spa
求最長時間的方法與UVa 562(http://www.cnblogs.com/lzj-0218/p/3565968.html)思路相同,用一個dp數組,dp[i]=true表示能夠錄出總長爲i的歌,dp[i]=false表示不能。而後對每首歌track[j],有dp[i]=dp[i-track[j]]3d
列出歌曲的方法就是再加一個數組pos,若dp[i-track[j]]=true,那麼能夠由狀態轉移方程推出dp[i]=true,這時就記錄下pos[i]=j,所有算完以後,倒着推回去便可code
1 #include<iostream> 2 #include<cstdio> 3 #include<stack> 4 #include<cstring> 5 6 using namespace std; 7 8 int n,number; 9 int track[30],pos[1000000]; 10 bool dp[1000000]; 11 12 int main() 13 { 14 while(scanf("%d",&n)==1) 15 { 16 scanf("%d",&number); 17 for(int i=0;i<number;i++) 18 scanf("%d",&track[i]); 19 20 memset(pos,-1,sizeof(pos)); 21 memset(dp,false,sizeof(dp)); 22 dp[0]=true; 23 24 for(int i=0;i<number;i++) 25 { 26 for(int j=n;j>=track[i];j--) 27 if(dp[j-track[i]]&&!dp[j]) 28 { 29 dp[j]=true; 30 pos[j]=i; 31 } 32 } 33 34 int sum; 35 stack<int> s; 36 37 for(int i=n;i>=0;i--) 38 if(dp[i]) 39 { 40 sum=i; 41 break; 42 } 43 44 int p=pos[sum],temp=sum; 45 while(p!=-1) 46 { 47 s.push(track[p]); 48 temp-=track[p]; 49 p=pos[temp]; 50 } 51 52 while(!s.empty()) 53 { 54 printf("%d ",s.top()); 55 s.pop(); 56 } 57 printf("sum:%d\n",sum); 58 } 59 60 return 0; 61 }