[프로그래머스/Python] 짝지어 제거하기
·
Algorithm/Programmers
def solution(s): answer = -1 stack = [s[0]] for i in s[1:]: if stack and stack[-1] == i: stack.pop() continue stack.append(i) answer = 1 if not stack else 0 return answer 연속인 문자를 어떻게 체크할까? 스택에 문자를 넣어줄 때, 맨 위 top 원소가 같은 문자인지 체크하면 된다. 같은 원소라면, pop해서 꺼내주고, 아니라면 append 한다. 모든 문자를 넣어주고 stack이 비어 있으면 짝지어 제거가 가능하므로 1 리턴, 그 외는 0 리턴이다. +) 그리고 미친 풀이 class ALWAYS_CORRECT(object): def __eq__(self,other): re..
[백준/Python] 2170 - 선 긋기
·
Algorithm/BaekJoon
import sys input = sys.stdin.readline spots = [] for _ in range(int(input())): s, e = map(int, input().split()) spots.append((s,e)) spots.sort(key= lambda x: x[0]) stack = [] for s, e in spots: if not stack or stack[-1] < s: stack.append(s) stack.append(e) else: if stack[-1] < e: stack.pop() stack.append(e) result = 0 for i in range(0, len(stack)-1, 2): s, e = stack[i], stack[i+1] result += abs(..
[백준/Python] 1874번 - 스택 수열
·
Algorithm/BaekJoon
import sys input = sys.stdin.readline n = int(input()) result = [] stack = [] i = 1 for _ in range(n): target = int(input()) if not stack or stack[-1] < target: for num in range(i, target + 1): stack.append(num) result.append('+') i = target + 1 if stack[-1] == target: stack.pop() result.append('-') else: break if stack: print('NO') else: print(*result, sep='\n') 문제에서 하라는 대로 따라가면서 풀면 된다. 그리고 어떤 ..
[백준/Python] 2493번 - 탑
·
Algorithm/BaekJoon
import sys input = sys.stdin.readline n = int(input()) b = list(map(int, input().split())) ## 틀린 풀이 # 수신한 탑들의 번호 출력 result = [0] h = 0 # 가장 높은 빌딩의 index for i in range(1,n): if b[h] > b[i]: result.append(h+1) else: result.append(0) # 뒤 차례 기준, 가장 가깝고 + 높은 빌딩 if i != n -1 and b[i] > b[i + 1]: h = i print(*result) 처음에 했던 틀린 풀이... 틀렸습니다가 떴다. 당연했던게 바로 왼쪽 빌딩 1개만 보고, 현재 빌딩보다 높지않으면 0을 넣어준다. 왼쪽에 있는 다른 빌딩..
[백준/Python] 10828번 - 스택
·
Algorithm/BaekJoon
import sys input = sys.stdin.readline stack = [] for _ in range(int(input())): commands = input().rstrip().split() if commands[0] == "push": stack.append(int(commands[1])) elif commands[0] == "pop": print(-1) if not stack else print(stack.pop()) elif commands[0] == "size": print(len(stack)) elif commands[0] == "empty": print(0) if stack else print(1) elif commands[0] == "top": print(stack[-1] if..
[백준/Python] 15903번 - 카드 합체 놀이
·
Algorithm/BaekJoon
import sys input = sys.stdin.readline import heapq n, m = map(int, input().split()) cards = [i for i in map(int, input().split())] heapq.heapify(cards) for _ in range(m): x = heapq.heappop(cards) y = heapq.heappop(cards) heapq.heappush(cards, x+y) heapq.heappush(cards, x+y) print(sum(cards)) 우선 순위 큐를 이용하면 쉽게 풀 수 있는 문제였다!