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;
}