반응형
문제 출처
한국정보올림피아드 지역본선 2015 중등부 2번
한국정보올림피아드 지역본선 2015 초등부 3번
문제 주소
알고리즘
스택
힌트
레이저가 있는 위치에 막대기가 몇 개 있는지 알면 계산할 수 있다.
문제풀이
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.data.append(item)
def pop(self):
if self.isEmpty() is not True:
return self.data.pop()
def peek(self):
if self.isEmpty() is not True:
return self.data[-1]
else:
print("Stack is empty")
return None
def print_list(self):
print(self.data)
def count_bar(bars):
st=ArrayStack()
ch = ArrayStack()
num=1
for i in range(len(bars)):
if bars[i] == '(':
st.push(num)
ch.push(num)
num+=1
if bars[i] == ')':
if bars[i-1] == '(':
ch.pop()
num-=1
ch.push('*')
else :
ch.push(-st.pop())
result = 0
cnt=0
while not ch.isEmpty():
tmp=ch.pop()
if tmp == "*":
result+=cnt
elif tmp<0:
cnt+=1
result+=1
else :
cnt-=1
return result
count_bar(input()
반응형
'Problem Solve > Stack' 카테고리의 다른 글
[HackerEarth] Fun Game (python) (0) | 2020.05.21 |
---|