본문 바로가기

전체 글110

[알고리즘] 덱 백준 10866 (Python) 큐와 비슷하지만 덱은 양쪽에서 push, pop이 가능하다. 코드 import sys n = int(input()) deque = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push_front' : deque.insert(0,command[1]) elif command[0] == 'push_back' : deque.append(command[1]) elif command[0] == "pop_front" : if len(deque) == 0 : print(-1) else : print(deque.pop(0)) elif command[0] == "pop_back" : if len(deque) == 0 : pri.. 2022. 1. 16.
[알고리즘] 큐 백준 10845 (Python) queue 는 선입선출이라는 것을 기억하고 풀었다. 코드 import sys n = int(sys.stdin.readline()) queue = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push' : queue.insert(0,command[1]) elif command[0] == 'pop' : if len(queue) == 0: print(-1) else : print(queue.pop()) elif command[0] == 'size' : print(len(queue)) elif command[0] == 'empty' : if len(queue) == 0 : print(1) else : print(0).. 2022. 1. 14.
[알고리즘] 괄호 백준 9012 (Python) Stack을 pop 했을 때 top의 값이 감소하는 것을 이용하여 풀었습니다. 코드 import sys n = int(sys.stdin.readline()) for i in range(n) : stack = sys.stdin.readline() top = 0 for j in stack: if j == '(' : top += 1 elif j == ')' : top -= 1 if top 0 : print('NO') elif top == 0: print('YES') 입출력 2022. 1. 14.
[알고리즘] 스택 백준 10828 (Python) 코드 import sys n = int(sys.stdin.readline()) stack = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push': stack.append(command[1]) elif command[0] == 'pop': if len(stack) == 0: print(-1) else: print(stack.pop()) elif command[0] == 'size': print(len(stack)) elif command[0] == 'empty': if(len(stack)==0): print(1) else : print(0) elif command[0] == 'top': if len(stac.. 2022. 1. 14.
[알고리즘] K번째 수 백준 11004 (Python) 코드 import sys n, k = map(int, input().split()) arr = list(map(int,input().split())) arr.sort() print(arr[k-1]) 입출력 2022. 1. 14.
[알고리즘] 카드 백준 11652 (Python) 처음에는 길이가 n인 배열을 선언해서 카드 숫자에 해당하는 인덱스에 +1을 하려 했다. 하지만 sort함수를 사용하면 카드 숫자와 상관없이 정렬이 되어 정답이 0으로만 나온다. 이 문제를 해결하기 위해서 dictionary를 사용했다. 코드 import sys n = int(sys.stdin.readline()) card = {} for i in range(n): key = int(sys.stdin.readline()) if key in card.keys(): card[key] += 1 else: card[key] = 1 card = sorted(card.items(), key = lambda x : (-x[1], x[0])) print(card[0][0]) 입출력 2022. 1. 14.