본문 바로가기

Lesson 7. Stacks and Queues - StoneWall

반응형

1. 문제

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 an 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 an 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.


Write an efficient algorithm for the following assumptions:
  - 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]

 

높이가 다른 2차원 공간에 돌을 채우려고 한다.

공간을 채우기 위해 사용되는 최소한의 돌수는? 

 

2. 매개변수 조건

  • 공간의 가로 길이(N): 1 ~ 100,000
  • 높이(H): 1 ~ 1,000,000,000

 

3. 예제 분석

index: x축

array value: y축 (높이)

return value: 7

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

예제 배열 도식화

 

문제에서도 예제에 관한 참고 그림이 있지만, 좀 더 자세히 그려보면 위와 같다.

이제 규칙을 찾아보자.

  • 같은 값이 나란히 오면, 하나의 돌로 처리할 수 있다. (H[0], H[1])
  • 다음 값(높이)이 작다면, 새로운 돌을 놓아야 한다. (H[2], H[5], H[7])
  • 다음 값(높이)이 크다면, 기존 돌 위에 돌을 추가로 쌓아야 한다. (H[3], H[4], H[8])
  • 돌을 쌓고 빼는 모양이, stack과 유사하다. (H[8])

 

4. 코드 (C++)

#include <stack>

int solution(vector<int> &H) {
    
    stack<int> stones = {};
    int cnt = 0;
    stones.push(H[0]);

    for(size_t i = 1; i < H.size(); i++)
    {
        if(stones.top() <= H[i])
        {
            if(stones.top() != H[i]) stones.push(H[i]);
        }
        else
        {
            do
            {
                stones.pop();
                cnt++;
                if(stones.empty()) 
                {
                    stones.push(H[i]);
                    break;
                }
            }while(stones.top() > H[i]);

            if(stones.top() != H[i]) stones.push(H[i]);
        }
    }

    return cnt + stones.size();
}

 

반응형