목록분류 전체보기 (108)
1seul357
import sys def Find(x): # 부모 노드 찾기 if P[x] != x: P[x] = Find(P[x]) return P[x] def Union(a, b): # 합집합 pa = Find(a) pb = Find(b) P[pb] = pa N, M = map(int, sys.stdin.readline().split()) P = [i for i in range(N+1)] # 부모 노드 값 저장할 리스트 생성 for i in range(M): z, a, b = map(int, sys.stdin.readline().split()) if z == 0: # 0이면 합집합으로 만들기 if Find(a) == Find(b): # 이미 같은 집합에 속해 있는 경우 continue # 넘기기 Union(a, b..
def dfs(now, cnt): for i in range(N+1): # 노드가 연결되어 있고, 아직 방문하지 않은 노드라면 if tree[now][i] != 0 and visited[i] == 0: if l == i: # 만약 노드가 자기 자신이면 continue # 넘어가기 visited[i] = cnt + tree[now][i] # 노드 사이의 거리 저장 dfs(i, cnt+tree[now][i]) N, M = map(int, input().split()) tree = [[0]*(N+1) for _ in range(N+1)] for i in range(N-1): a, b, c = map(int, input().split()) # 트리 상의 연결된 두 점과 거리 입력받기 tree[a][b] = tr..
N, M = map(int, input().split()) array = [input() for _ in range(N)] arr = [input() for _ in range(M)] count = 0 for tmp in arr: # arr 리스트에서 문자열 하나씩 꺼내서 if tmp in array: # array에 있는지 확인하고, count += 1 # 있으면 + 1 print(count) 문제 풀이 시간이 엄청 오래 걸리지만 통과하기는 함. 집합 S에 들어가는 문자열(array)은 똑같은 문자열들이 있다. 그래서 set을 통해 중복되는 문자열을 제거하면 빠르게 통과할 수 있다. set([input() for _ in range(N)])
# 삭제되는 노드와 연결되어 있는 노드들의 값을 -2로 바꿔주기 위한 dfs def dfs(tmp): for i in range(0, len(tree)): # 아직 노드를 방문하지 않았고, tree에 저장된 값이 삭제되는 부모 노드가 맞으면 if visited[i] == 0 and tree[i] == tmp: visited[i] = 1 # 방문 체크 temp = tmp # dfs 탐색이 끝난 후에 값 원래대로 바꿔야하므로 tmp를 temp에 저장 tmp = i # tmp에 새로운 부모 노드 저장 tree[i] = -2 # tree 값을 -2로 바꾸기 (삭제되는 노드) dfs(tmp) tmp = temp # 값 원래대로 바꾸기 (값을 안바꾸면 왼쪽 자식 노드만 제대로 탐색됨) N = int(input())..
TC = int(input()) for tc in range(TC): N, M = map(int, input().split()) arr = list(map(int, input().split())) # 우선순위 입력받기 q = [[0]*2 for _ in range(N)] # 우선순위와 인덱스 값을 새롭게 저장할 이차원 리스트 cnt = 0 # 문서가 몇 번째로 인쇄되는지 체크할 변수 for i in range(N): q[i][0] = arr[i] # q에 첫번째 인덱스에는 우선순위를 저장하고, q[i][1] = i # 두번째 인덱스에는 인덱스 값을 저장함 while True: x, y = max(q) if q[0][0] == x: # q에 맨 앞에 있는 값이 최댓값이라면 if q[0][1] == M: #..
from collections import deque def bfs(a, b): global o_cnt, v_cnt dr = [0, 0, -1, 1] dc = [-1, 1, 0, 0] q.append([a, b]) while q: # q에 값이 있으면 반복 x, y = q.popleft() for i in range(4): now_dr = x + dr[i] now_dc = y + dc[i] if 0
answer = [] def dfs(isvisited, now, route, cnt, li): if cnt == len(route): # 모든 경로를 탐색했으면 answer.append(li) # answer에 추가 return for i in range(len(route)): # 아직 방문 안했고, 다음 공항으로 이동할 수 있다면 if isvisited[i] == 0 and now == route[i][0]: isvisited[i] = 1 # 방문 체크 dfs(isvisited, route[i][1], route, cnt+1, li+[route[i][1]]) # dfs 탐색 isvisited[i] = 0 # 다시 0으로 def solution(tickets): tickets.sort() # 알파벳 순으..