문제풀이 324

[백준][자료구조/힙] 1655.가운데를 말해요 (파이썬/Python)

import heapq import sys input = sys.stdin.readline n = int(input()) h = [] for _ in range(n): x = int(input()) if x != 0: heapq.heappush(h,(abs(x),x)) else: try: print(heapq.heappop(h)[1]) except: print(0) # heap에 들어간 heap[1]값을 빼야 절대값이 씌워진 수가 아닌 본래 우리가 넣었던 수를 pop할 수 있기 때문에 h[1]을 빼내주는 것이다.

[백준][자료구조/힙] 1655.가운데를 말해요 (파이썬/Python)

import sys import heapq input = sys.stdin.readline n=int(input()) leftHeap=[] rightHeap=[] answer=[] for i in range(n): num=int(input()) if len(leftHeap)==len(rightHeap): heapq.heappush(leftHeap, (-num, num)) else: heapq.heappush(rightHeap, (num, num)) if rightHeap and leftHeap[0][1] > rightHeap[0][0]: min=heapq.heappop(rightHeap)[0] max=heapq.heappop(leftHeap)[1] heapq.heappush(leftHeap, (-min,..

[백준][자료구조/힙] 1927.최소 힙 (파이썬/Python)

import heapq import sys input = sys.stdin.readline n = int(input()) heap = [] for _ in range(n): x = int(input()) if x != 0: heapq.heappush(heap,x) else: try: print(heapq.heappop(heap)) except: print(0) [자료구조와 함께 배우는 알고리즘][정렬 알고리즘] - 힙 정렬(Heap Sort) 1. 힙 정렬 알아보기 힙 정렬은 힙의 특성을 이용해 정렬하는 알고리즘이다. 힙은 '부모의 값이 자식의 값보다 항상 크다'는 조건을 만족하는 완전 이진 트리이다. 이때 부모의 값이 자식의 값보 yeomylaoo.tistory.com 힙에 대해서 정리해놓은 것이기 때..

[백준][구현] 1009.분산처리 (파이썬/Python)

T = int(input()) for _ in range(T): a, b = map(int, input().split()) a = a % 10 if a == 0: print(10) elif a == 1 or a == 5 or a == 6: print(a) elif a == 4 or a == 9: b = b % 2 if b == 1: print(a) else: print((a * a) % 10) else: b = b % 4 if b == 0: print((a**4) % 10 % 10 % 10) else: print((a**b) % 10 % 10 % 10) # 거듭 제곱에 런타임에러가 나기 때문에 규칙을 잘 보면 답이 나오는 문제

[프로그래머스][Lv2] - 소수 찾기(파이썬/Python)

from itertools import permutations def solution(numbers): a = set() #중복을 방지하기 위해서 set으로 설정 #순열을 사용해서 사용가능한 조합을 모두 찾아준 뒤 진행한다. for i in range(len(numbers)): a |= set(map(int, map("".join, permutations(list(numbers), i + 1)))) a -= set(range(0,2)) for i in range(2,int(max(a)**0.5)+1): a -= set(range(i*2,max(a)+1,i)) return len(a)

[백준][Dijkstra/다익스트라] 4885. 녹색 옷 입은 애가 젤다지? (파이썬/Python)

import heapq import sys INF =int(1e9) input = sys.stdin.readline dx = [0,0,-1,1] dy = [1,-1,0,0] tastcase = 1 def dijsktra(): q = [] heapq.heappush(q,(graph[0][0],0,0)) #cost, 시작위치 graph[0][0]을 넣어줌 dist[0][0] = 0 while q: cost, x,y = heapq.heappop(q) if x == n-1 and y == n-1: #도착했다면? print(f"Problem {tastcase}: {dist[x][y]}") break for i in range(4): nx = x + dx[i] ny = y + dy[i] if 0