Cdtime limit:3000msmemory limit:131072kbthis problem'll be judged onUVA. Original id:624
64-bit integer IO format: %lld Java class name: Main
You had a long drive by car ahead. You had a tape recorder, but the unfortunately your best music was on CDs. You need to has it on tapes so the problem to solve is:you has a tape N minutes long. How to choose tracks from CD to get the most out of tape space and has 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 was 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 is stored On the CD
InputAny 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
OutputSet of tracks (and durations) which is the correct solutions and string "sum:" and sum of duration times.
Sample Input
5 3 1 3 410 4 9 8 4 220 4 10 5 7 490 8 10 23 1 2 3 4 5 745 8 4 10 44 43 12 9 8 2
Sample Output
1 4 sum:58 2 sum:1010 5 4 sum:1910 1 2 3 4 5 7 sum:554 ten 9 8 2 sum:45
Problem Solving: 01 Backpack + Print Path
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <stack>5 using namespacestd;6 Const intMAXN =10001;7 intdp[ -][maxn],dur[maxn],n,m;8stack<int>ans;9 intMain () {Ten while(~SCANF ("%d%d",&m,&N)) { One for(inti =1; I <= N; ++i) Ascanf"%d", dur+i); -Memset (DP,0,sizeof(DP)); - while(!ans.empty ()) Ans.pop (); the for(inti =1; I <= N; ++i) { - for(intj = m; J >=0; --j) { - if(J >= Dur[i]) dp[i][j] = max (dp[i][j],dp[i-1][j-dur[i]] +dur[i]); -DP[I][J] = max (dp[i][j],dp[i-1][j]); + } - } + intRET =Dp[n][m]; A for(inti = n; I && m; --i) at if(dp[i][m]! = dp[i-1][m]) { - Ans.push (Dur[i]); -M-=Dur[i]; - } - while(!Ans.empty ()) { -printf"%d", Ans.top ()); in Ans.pop (); - } toprintf"sum:%d\n", ret); + } - return 0; the}
View Code
UVA 624 CD