반응형

문제 출처 :


https://www.acmicpc.net/problem/2605



알고리즘 분석 :


문제 해결에 필요한 사항

1. Stack 이용


이 문제에서 스택을 이용해야 된다는 생각을 잡아낼 수 있는부분은 1이 계속 뒤로 밀려나는 과정에서 알 수 있다. (LIFO 형식)


그림을 통해 문제의 예제 입력에 따른 예제 출력의 과정을 확인해보도록 하자.











마지막 스택 뒤집기는 s에 있는 값을 tmp로 옮기고 tmp를 출력하면 s가 거꾸로 쌓이게 된다.


소스 코드 : 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <stack>
 
using namespace std;
 
int main()
{
    int n;
    int arr[101];
    stack<int> s;
    stack<int> tmp;
 
    cin >> n;
 
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    
        for (int j = 0; j < arr[i]; j++)
        {
            tmp.push(s.top());
            s.pop();
        }
 
        s.push(i+1);
 
        for (int j = 0; j < arr[i]; j++)
        {
            s.push(tmp.top());
            tmp.pop();
        }
    }
 
    // 스택 뒤집기
    while (!s.empty())
    {
        tmp.push(s.top());
        s.pop();
    }
 
    // 출력
    while (!tmp.empty())
    {
        printf("%d ", tmp.top());
        tmp.pop();
    }
 
    return 0;
}
 


//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus

반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[9465번] 스티커  (0) 2016.10.28
[1212번] 8진수 2진수  (2) 2016.10.28
[2790번] F7  (0) 2016.10.27
[2875번] 대회 or 인턴  (0) 2016.10.24
[2193번] 이친수  (0) 2016.10.14