ACM: 动态规划题 poj&nb…

来源:互联网 发布:金山tw域名遭抢注 编辑:程序博客网 时间:2024/06/06 01:58
SpaceElevator

Description

The cows are going to space!They plan to achieve orbit by building a sort of space elevator: agiant tower of blocks. They have K (1 <= K<= 400) different types of blocks with which tobuild the tower. Each block of type i has height h_i (1<= h_i <= 100) and is available inquantity c_i (1 <= c_i <= 10). Due topossible damage caused by cosmic rays, no part of a block of type ican exceed a maximum altitude a_i (1 <= a_i<= 40000).

Help the cows build the tallest space elevator possible by stackingblocks on top of each other according to the rules.

Input

* Line 1: A single integer,K

* Lines 2..K+1: Each line contains three space-separated integers:h_i, a_i, and c_i. Line i+1 describes block type i.

Output

* Line 1: A single integer H,the maximum height of a tower that can be built

Sample Input

3
7 40 3
5 23 8
2 52 6

Sample Output

48

 

题意: cows们打算去太空, 它们有K种不同types的材料建造升降舱, 每种材料有c_i个和

      每个高度h_i,但是有一个限制: 当用这种材料结束时升降舱高度不超过a_i. 现在

     要你求出升降舱最大高度.

 

解题思路:

     1. 明显背包问题, 并且是多重背包. 设状态dp[i][j]: 前面i中材料是否能不超过限制条件

        下(j背包容量), 放入背包中.

     2. 问题跟a_i有大小有关, 应该先对a_i排序, 小的先用.

     3. 因为每次使用新的材料只跟上一种有关, dp[i][j]降至一维dp[j]即可.

 

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX 40005
#define MAXSIZE 405

struct node
{
 int h, al, c;
}block[MAXSIZE];

int n;
bool dp[MAX];

inline int max(int a, int b)
{
 return a > b ? a : b;
}

bool cmp(node &a, node &b)
{
 return a.al < b.al;
}

int DP()
{
 int result = 0;
 dp[0] = true;
 for(int i = 1; i <= n; ++i)
 {
  for(int j = 1; j<= block[i].c; ++j)
  {
   for(int k =result; k >= 0; --k)
   {
    if(dp[k] )
    {
     if(k+block[i].h <= block[i].al )
     {
      dp[k+block[i].h ] = true;
      result= max(result, k+block[i].h);
     }
    }
   }
  }
 }
 return result;
}

int main()
{
// freopen("input.txt", "r", stdin);
 while(scanf("%d", &n) !=EOF)
 {
  for(int i = 1; i<= n; ++i)
   scanf("%d %d%d", &block[i].h, &block[i].al,&block[i].c);
  sort(block+1, block+n+1,cmp);

  memset(dp, false,sizeof(dp));
  printf("%d\n", DP());
 }
 return 0;
}

0 0