24h購物| | PChome| 登入
2012-04-04 09:12:28| 人氣1,363| 回應0 | 上一篇 | 下一篇

[UVA][DP] 624 - CD

推薦 0 收藏 0 轉貼0 訂閱站台


  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.


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

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 are 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
10 5 4 sum:19
10 23 1 2 3 4 5 7 sum:55
4 10 12 9 8 2 sum:45

0/1 背包問題,這題是 special judge 所以有多組解。
#include <stdio.h>
#include <string.h>

int main() {
int N, t, i, j;
int cdTime[20], DP[20001], source[20001];
while(scanf("%d %d", &N, &t) == 2) {
for(i = 0; i < t; i++)
scanf("%d", &cdTime[i]);
memset(DP, 0, sizeof(DP));
memset(source, 0, sizeof(source));
DP[0] = 1, source[0] = 0;
for(i = 0; i < t; i++) {
for(j = N-cdTime[i]; j >= 0; j--) {
if(DP[j+cdTime[i]] == 0 && DP[j] == 1) {
DP[j+cdTime[i]] = 1;
source[j+cdTime[i]] = cdTime[i];
}
}
}
int tmpN = N;
while(tmpN >= 0 && DP[tmpN] == 0) tmpN--;
N = tmpN;
int ans[20], aidx = 0;
while(tmpN) {
ans[aidx++] = source[tmpN];
tmpN -= source[tmpN];
}
for(i = 0; i < aidx; i++)
printf("%d ", ans[i]);
printf("sum:%d\n", N);
}
return 0;
}
 

台長: Morris
人氣(1,363) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][DP] 10502 - Counting Rectangles
此分類上一篇:[UVA] 10945 - Mother bear

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文