John is a diver and a treasure hunter. He has just found the location of a pirate ship full of treasures. The sofisticated sonar system on board his ship allows him to identify the location, depth and quantity of gold in each suken treasure. Unfortunatelly, John forgot to bring a GPS device and the chances of ever finding this location again are very slim so he has to grab the gold now. To make the situation worse, John has only one compressed air bottle.
John wants to dive with the compressed air bottle to recover as much gold as possible from the wreck. Write a program John can use to select which treasures he should pick to maximize the quantity of gold recovered.
The problem has the following restrictions:
The input to this program consists of a sequence of integer values. Input contains several test cases. The first line of each dataset should contain the values t and w. The second line contains the number of treasures. Each of the following lines contains the depth di and quantity of gold viof a different treasure.
A blank line separates each test case.
The first line of the output for each dataset should contain the maximum amount of gold that John can recover from the wreck. The second line should contain the number of recovered treasures. Each of the following lines should contain the depth and amount of gold of each recovered treasure. Treasures should be presented in the same order as the input file.
Print a blank line between outputs for different datasets.
210 4 3 10 5 10 1 7 2
In this sample input, the bottle of compressed air has a capacity of 200 seconds, the constant whas the value 4 and there are 3 treasures, the first one at a depth of 10 meters and worth 5 coins of gold, the second one at a depth of 10 meters and worth 1 coin of gold, and the third one at 7 meters and worth 2 coins of gold.
7 2 10 5 7 2
#include <cstdio> #include <cstring> const int MAX = 5000; int t,w, n; int d[MAX], v[MAX]; int dp[MAX][MAX], ans[MAX]; int max(int a, int b) { return a>b?a:b; } int main() { // freopen("in.txt","r",stdin); int nCase=0; while(scanf("%d %d", &t, &w)==2) { if(nCase) puts(""); scanf("%d", &n); for(int i=1; i <= n; i++) scanf("%d %d", &d[i], &v[i]); memset(dp,0,sizeof(dp)); for(int i=1; i <= n; i++) { for(int j=0; j <= t; j++) { int temp = d[i]*w*3; if(j >= temp) dp[i][j]=max(dp[i-1][j], dp[i-1][j-temp]+v[i]); else dp[i][j] = dp[i-1][j]; } } int length=0; for(int i=n, j=t; i>0; i--) { int temp = d[i]*w*3; if(j-temp>=0 && dp[i][j]==dp[i-1][j-temp]+v[i]) { ans[length++] = i; j -= temp;//这里写成 j-=v[i]了 WA了4次 } } printf("%d\n", dp[n][t]); printf("%d\n", length); for(int i=length-1; i>=0; i--) printf("%d %d\n", d[ans[i]], v[ans[i]]); nCase++; } return 0; }
WA 了五次,一个是格式,一个是写快了,唉
UVa 990 - Diving for Gold DP 0-1,布布扣,bubuko.com
UVa 990 - Diving for Gold DP 0-1
原文:http://blog.csdn.net/china_zoujinyong/article/details/20362973