본문 바로가기
백준

26111: Parentheses Tree [백준 - Python]

by 청원뿔세포 2023. 10. 3.

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

 

26111번: Parentheses Tree

A rooted ordered tree $T$ can be expressed as a string of matched parentheses $p(T)$. The string representation $p(T)$ can be defined recursively. As a base case, a tree consisting of a single node is expressed by a pair of parentheses (). When a rooted or

www.acmicpc.net

 

소괄호 리스트가 입력으로 주어졌을 때, "()"형태의 괄호가 어느정도 깊이에 있는지를 알아내여 그 값들의 합을 구하는 문제이다.

((()()())())

1번 예제의 경우 위 그림처럼 1,2,3번째 "()"괄호는 2층 깊이에 있고 마지막 괄호는 1층깊이에 있다.

 

(()((()(()))()))

2번 예제의 경우는 첫번째는 1층깊이, 두번째는 3층깊이, 세번째는 4층깊이, 마지막은 2층깊이에 위치한다.

 

코드를 짜기 위해서 변수 2개를 정한다.

level은 현재 몇층인지를 저장할 것이고, result는 "()"형태가 나타나면 결과를 더해줄 변수이다.

 

t = input()
 
level = -1
result = 0
 
for i in range(len(t)):
    if t[i] == '(':
        level+=1
    elif t[i] ==')':
        if t[i-1] == '(':
            result += level
            level -=1
        else:
            level -=1
       
print(result)

 

 

 

 

 

 

 

 

 

 

댓글