문제풀이 324

[백준][BFS] 1389. 케빈 베이컨의 6단계 법칙 (파이썬/Python)

import sys input = sys.stdin.readline from collections import deque def bfs(graph,start): q = deque() q.append(start) visited[start] = 1 distance = [0] * (n+1) while q: x = q.popleft() for i in graph[x]: if visited[i] == 0: distance[i] = distance[x] + 1 q.append(i) visited[i] = 1 return sum(distance) n,m = map(int,input().split()) answer = [] graph = [[] for _ in range(n+1)] for _ in range(m): a..

[백준][자료구조/힙] 1202. 보석도둑(파이썬/Python)

import sys import heapq input = sys.stdin.readline n,k = map(int,input().split()) bag = [] jewely = [] candidate = [] answer = 0 for _ in range(n): weight, price = map(int,input().split()) heapq.heappush(jewely,[weight,price]) for _ in range(k): bag.append(int(input())) bag.sort() for i in bag: while jewely and i >= jewely[0][0]: weight, price = heapq.heappop(jewely) heapq.heappush(candidate,-pr..

[백준][자료구조/힙] 1766.문제집 (파이썬/Python)

import sys import heapq n,m = map(int,input().split()) B_list = [[] for _ in range(n+1)] check = [0 for _ in range(n+1)] heap = [] answer = [] for _ in range(m): a,b = map(int,input().split()) B_list[a].append(b) check[b] += 1 for i in range(1,n+1): if check[i] == 0: heapq.heappush(heap,i) while heap: now = heapq.heappop(heap) answer.append(now) for i in B_list[now]: check[i] -= 1 if check[i] ==..

[백준][DFS/DP] 1707. 이분 그래프 (파이썬/Python)

import sys input = sys.stdin.readline from collections import deque def bfs(start): visited[start] = 1 q = deque() q.append(start) while q: x = q.popleft() for i in graph[x]: if visited[i] == 0: visited[i] = -visited[x] q.append(i) else: if visited[i] == visited[x]: return False return True k = int(input()) for _ in range(k): v,e = map(int,input().split()) graph = [[] for _ in range(v+1)] visite..

[백준][Dijkstra/다익스트라] 1504번.특정한 최단 경로 (파이썬/Python)

import heapq import sys input = sys.stdin.readline INF = int(1e9) v, e = map(int, input().split()) graph = [[] for _ in range(v + 1)] for _ in range(e): x, y, cost = map(int, input().split()) graph[x].append((y, cost)) graph[y].append((x, cost)) def dijkstra(start): distance = [INF] * (v + 1) q = [] heapq.heappush(q, (0, start)) distance[start] = 0 while q: dist, now = heapq.heappop(q) if distan..

[백준][DFS] 1967. 트리의 지름 (파이썬/Python)

import sys sys.setrecursionlimit(10**9) input = sys.stdin.readline n=int(input()) graph=[[] for _ in range(n+1)] for _ in range(n-1): p,c,cost=map(int,input().split()) graph[p].append([c,cost]) graph[c].append([p,cost]) result1=[0 for _ in range(n+1)] def DFS(start,graph,result): for e,d in graph[start]: if result[e]==0: result[e]=result[start]+d DFS(e,graph,result) DFS(1,graph,result1) result1[..