250x250
Notice
Recent Posts
«   2024/09   »
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
관리 메뉴

일상 코딩

[python] 백준 알고리즘 1874번 스택 수열 풀이 본문

코딩테스트/백준 online Judge

[python] 백준 알고리즘 1874번 스택 수열 풀이

polarcompass 2021. 11. 5. 00:02
728x90

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

 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

N = int(input())
count = 1
stack = []
result = ""

for _ in range(N):
    Answer = int(input())
    while count <= Answer:
        stack.append(count)
        count += 1
        result += "+\n"

    if stack[-1] == Answer:
        stack.pop()
        result += "-\n"
    else:
        print("NO")
        exit(0)

print(result, end=" ")

입력 예시1

8
4
3
6
8
7
5
2
1

출력 예시1

+
+
+
+
-
-
+
+
-
+
+
-
-
-
-
-

입력 예시2

5
1
2
5
3
4

출력 예시2

NO

정답 코드를 보고서 개선한 것은 

result += "+\n"

위 코드 정도이다.

파이썬에서 list.append() 연산이 시간을 꽤 잡아먹는다기에 

더하기 연산으로 바꿔 주었다.

문제 자체가 그렇게 연산을 많이 하는 것은 아니기에

영향은 미미하겠지만 나름 개선한다고는 해보았다.

728x90