Colidity-- StoneWall

最简单的思路就是:每次选最小的,算一块;然后对最小值左右两边递归的解子问题

加上备忘录应该能够转化为DP

但是我没有尝试

这里参考了一个贪心的算法

 1 // you can use includes, for example:
 2 // #include <algorithm>
 3 #include <stack>
 4 // you can write to stdout for debugging purposes, e.g.
 5 // cout << "this is a debug message" << endl;
 6 
 7 int solution(vector<int> &H) {
 8     // write your code in C++11
 9     int blocks = 0;
10     size_t i = 0;
11     stack<int> blocks_stack;
12     
13     for(i = 0; i < H.size(); ++i)
14     {
15         while(!blocks_stack.empty() && H[i] < blocks_stack.top())
16         {
17             blocks_stack.pop();
18         }
19     
20         if(blocks_stack.empty() || H[i] > blocks_stack.top())
21         {
22             blocks_stack.push(H[i]);
23             ++blocks;
24         }
25     }
26     
27     return blocks;
28 }

Solution to this task can be found at our blog.

You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by a zero-indexed array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

int solution(vector<int> &H);

that, given a zero-indexed array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

  H[0] = 8    H[1] = 8    H[2] = 5    
  H[3] = 7    H[4] = 9    H[5] = 8    
  H[6] = 7    H[7] = 4    H[8] = 8    

the function should return 7. The figure shows one possible arrangement of seven blocks.

Assume that:

  • N is an integer within the range [1..100,000];
  • each element of array H is an integer within the range [1..1,000,000,000].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

转载于:https://www.cnblogs.com/cane/p/3976576.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值