UVA 624 CD
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:
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
Input
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
Output
Set of tracks (and durations) which is the correct solutions and string "sum:" and sum of duration times.
Sample Input
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
Sample Output
1 4 sum:5
8 2 Sum:10
5 4 sum:19
1 2 3 4 5 7 sum:55
4 9 8 2 sum:45
The main topic: Each row is a set of data, the first two numbers of each group of N, M, the target number and the number of data, followed by M data. The number of the closest target number that is required to be composed of M data. Outputs the number, and the number that makes up the number. (Only one time per number). Solution: 01 backpack. Be aware that each number can be used only once. And the answer is not unique.
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>typedef Long Longllusing namespace STD;intnum[ -];intdp[100005], rec[100005], r[ -];intMain () {intN, M, CNT; while(scanf("%d%d", &n, &m) = =2) {cnt =0;memset(Num,0,sizeof(num));memset(DP,0,sizeof(DP));memset(REC,0,sizeof(rec)); for(inti =0; I < m; i++) {scanf("%d", &num[i]); } dp[0] =1; for(inti =0; I < m; i++) { for(intj = N; J >=0; j--) {if(Dp[j] &&!dp[j + num[i]) {dp[j + num[i]] =1; Rec[j + num[i]] = num[i]; } } } while(!dp[n]) n--;intt = N; while(N >=0&& Rec[n]) {r[cnt++] = Rec[n]; N-= Rec[n]; } for(inti = cnt-1; I >=0; i--) {printf("%d", R[i]); }printf("sum:%d\n", t); }return 0;}
UVA 624 CD (01 backpack)