Codility-StoneWall

本文探讨了如何使用最少数量的石块构建一面高度变化的墙。通过分析墙面高度数组,利用贪心算法确定每块石块的最佳位置,确保整体使用的石块数量达到最小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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(const 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.

分析: 这个问题实际上叫做skyline problem。初步想想挺复杂,其实一个贪心足以搞定。我个人觉得直方图最大矩形的那个题的思想很重要,它的思想可以解决很多问题,而且是O(n)的。我们按最大矩形的方法来想,贪心: 对每个块,考虑它左边的块,直到某一块不比它高。这中间所有块都比它高,我们可以把这些块按照新块的高度设置一个矩形……矩形个数决定于最先那个块是比它矮,还是和她一样高。这样贪心的话,我们的矩形尽可能长,而且产生一个新块的时候无论如何我们都可能增加一个矩形,把这个矩形和左边的连起来还可能少一个矩形,所以不严格的证明,贪心是正确地。

// you can use includes, for example:
// #include 
#include 
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(const vector &H) {
    // write your code in C++11
    stack iStack;
    int cnt=0;
    for(unsigned int i=0;iiStack.top())
        {
            cnt++;
            iStack.push(H[i]);
        }
    }
    return cnt;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值