백준 1874 스택 수열

빵동·2023년 7월 11일

알고리즘

목록 보기
1/2
# n은 100,000 n2으로는 안풀림
import sys

class StackPermutation():

    def __init__(self):
        self.MAX =None
        self.goals = []
        self.goalIdx = 0
        self.curr = 1
        self.stack = []

        self.logs = []
        self.result = []

    def getNum(self):
        curr = self.curr
        self.curr +=1
        return curr

    def getCurrNum(self):
        return self.curr

    def setNextGoal(self):
        self.goalIdx += 1
    def getNextGoal(self):
        self.goalIdx += 1
        return self.goals[self.goalIdx]

    def getCurrGoal(self):
        return self.goals[self.goalIdx]

    def getLast(self):
        if len(self.stack) == 0:
            return None
        return self.stack[-1]

    def printLog(self):
        for log in self.logs:
            print(log)
    def run(self):

        while True:

            if self.curr == self.MAX+1 and len(self.stack)==0:
                break
            if self.curr > self.MAX+1:
                break


            currGoal = self.getCurrGoal() #4
            lastVal = self.getLast() # 1 2 3 4

            if currGoal != lastVal:
                self.stack.append(self.getNum())
                self.logs.append('+')

            elif currGoal == lastVal:
                popVal = self.stack.pop()
                self.logs.append('-')
                self.result.append(popVal)
                self.setNextGoal()

        if self.result == self.goals:
            self.printLog()
        else:
            print('NO')


n, *arr = map(int, sys.stdin.buffer.read().splitlines())
sp = StackPermutation()
sp.MAX = int(n)
sp.goals = arr
sp.run()





0개의 댓글