ACM: dp题 --> 背包问题 poj 1837

来源:互联网 发布:深圳阿里云大厦 编辑:程序博客网 时间:2024/05/27 09:45

                                                                         Balance

Description

Gigel has a strange "balance" and he wants to poise it.Actually, the device is different from any other ordinarybalance.
It orders two arms of negligible weight and each arm's length is15. Some hooks are attached to these arms and Gigel wants to hangup some weights from his collection of G weights (1<= G <= 20) knowing that theseweights have distinct values in the range 1..25. Gigel may droopany weight of any hook but he is forced to use all theweights.
Finally, Gigel managed to balance the device using the experiencehe gained at the National Olympiad in Informatics. Now he wouldlike to know in how many ways the device can be balanced.

Knowing the repartition of the hooks and the set of the weightswrite a program that calculates the number of possibilities tobalance the device.
It is guaranteed that will exist at least one solution for eachtest case at the evaluation.

Input

The input has the following structure:
• the first line contains the number C (2 <= C<= 20) and the number G (2 <= G<= 20);
• the next line contains C integer numbers (these numbers are alsodistinct and sorted in ascending order) in the range -15..15representing the repartition of the hooks; each number representsthe position relative to the center of the balance on the X axis(when no weights are attached the device is balanced and lined upto the X axis; the absolute value of the distances represents thedistance between the hook and the balance center and the sign ofthe numbers determines the arm of the balance to which the hook isattached: '-' for the left arm and '+' for the right arm);
• on the next line there are G natural, distinct and sorted inascending order numbers in the range 1..25 representing theweights' values.

Output

The output contains the number M representing the number ofpossibilities to poise the balance.

Sample Input

2 4

-2 3

3 4 5 8

Sample Output

2

 

题意: 现在给你力距值C个, 砝码的g个的重量. 现在要你求是杠杆平衡的次数.

 

解题思路:

               1. 题目是明显的动态规划-->背包问题. 先找出状态转移方程.

               2. 设dp[i][j] 表示前i个物品距离平衡的重量.

                 方程:  dp[i][j] = dp[i-1][j-dis[k]*w[i-1]];

 

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 7505

int c, g;
int cc[25], gg[25];
int dp[22][MAX*2];

int main()
{
//   freopen("input.txt","r",stdin);
   while(scanf("%d%d",&c,&g) != EOF)
    {
      for(int i = 0; i < c; ++i)
         scanf("%d",&cc[i]);
      for(int i = 0; i < g; ++i)
         scanf("%d",&gg[i]);
      memset(dp,0,sizeof(dp));
      dp[0][7500] = 1;
      
      for(int i = 1; i <= g; ++i)
      {
         for(int j = -7500; j <= 7500;++j)
         {
            for(int k = 0; k < c; ++k)
               dp[i][j+7500] +=dp[i-1][j+7500-cc[k]*gg[i-1]];
         }
      }
      printf("%d\n",dp[g][7500]);
    }
    return0;
}

0 0
原创粉丝点击