欢迎访问我的个人网站==》 jiashubing.cn

HUST 1018 Two thieves (背包动态规划)

Two thieves

Time Limit: 3 Sec  Memory Limit: 128 MB
Submissions: 334  Solved: 62

Description

There are two thieves, both of them have a bag whose capacity is CAP (1<= CAP <= 512). And there are N (N <= 128) diamonds, each of them have a weight w and a value v (1 <= w,v <= 512). The consecutive diamonds can not be put in the same bag.
The two greedy thieves want to earn as mush value as possible. Can you help them to solve this tough work?

Input

There are multiply test cases.
The first line: three integers N, CAP1, CAP2;
The following N lines: each line with two integers w, v.

Output

The total value of the diamonds which have been stolen by the two thieves.

Sample Input

3 9 19
4 5
7 10
8 9

Sample Output

24

三维背包问题,动态规划
题目大意:帮两个小偷取得最大价值的珠宝,而且
背包不能超重
思路:dp[i][j][k]表示当第一个背包里放重量恰为i,第二个背包里放重量恰为j时,当前物品放在k号背包里所得到的最大价值,k=0表示两个背包都不放
状态转移是:dp[i][j][0] = max(dp[i][j][0],dp[i][j][1],dp[i][j][2]);
      dp[i][j][1] = max(dp[i-w[k]][j][0],dp[i-w[k]][j][2])+v[k];
      dp[i][j][2] = max(dp[i][j-w[k]][1],dp[i][j-w[k]][0])+v[k];
边界条件是:
  dp[0][0][0]=0;  dp[w[0]][0][1] = v[0];  dp[0][w[0]][2] = v[0];
 
View Code
 1 # include<stdio.h>
 2 # include<string.h>
 3 int dp[520][520][3];
 4 int v[150],w[150];
 5 int max(int a,int b){
 6     return a>b?a:b;
 7 }
 8 int main()
 9 {
10     int i,j,k,m1,m2,n;
11     while(scanf("%d%d%d",&n,&m1,&m2)!=EOF)
12     {
13         memset(dp,0,sizeof(dp));
14         for(i=0;i<n;i++)
15             scanf("%d%d",&w[i],&v[i]);
16         dp[0][0][0]=0;
17         dp[w[0]][0][1] = v[0];
18         dp[0][w[0]][2] = v[0];
19         for(k=1;k<n;k++)
20         {
21             for(i=m1;i>=0;i--)
22             {
23                 for(j=m2;j>=0;j--)
24                 {
25                     dp[i][j][0]=max(max(dp[i][j][0],dp[i][j][1]),dp[i][j][2]);
26                     if(i-w[k]>=0) dp[i][j][1] = max(dp[i-w[k]][j][0],dp[i-w[k]][j][2])+v[k];
27                     if(j-w[k]>=0) dp[i][j][2] = max(dp[i][j-w[k]][1],dp[i][j-w[k]][0])+v[k];
28                 }
29             }
30         }
31         int ans=0;
32         for(i=0;i<=m1;i++)
33             for(j=0;j<=m2;j++)
34                 for(k=0;k<3;k++)
35                     if(dp[i][j][k]>ans)
36                         ans=dp[i][j][k];
37                     printf("%d\n",ans);
38     }
39     return 0;
40 }

 

 
posted @ 2013-04-27 16:19  贾树丙  阅读(304)  评论(0编辑  收藏  举报