diff --git a/lily/week_4/boj_10866.py b/lily/week_4/boj_10866.py new file mode 100644 index 0000000..4754007 --- /dev/null +++ b/lily/week_4/boj_10866.py @@ -0,0 +1,47 @@ +import sys + +def is_deq_empty(deq): + return len(deq) == 0 + +readline = sys.stdin.readline +action_num = int(input()) +deq = [] +for _ in range(action_num): + inputs = list(map(str, readline().split())) + action = inputs[0] + if len(inputs) == 2: + digit = int(inputs[1]) + if action == "push_front": + deq.insert(0, digit) + else: # "push_back" + deq.append(digit) + else: + if action == "pop_front": + if is_deq_empty(deq): + print(-1) + else: + print(deq[0]) + deq.pop(0) + elif action == "pop_back": + if is_deq_empty(deq): + print(-1) + else: + print(deq[-1]) + deq = deq[:-1] + elif action == "size": + print(len(deq)) + elif action == "empty": + if is_deq_empty(deq): + print(1) + else: + print(0) + elif action == "front": + if is_deq_empty(deq): + print(-1) + else: + print(deq[0]) + else: # back + if is_deq_empty(deq): + print(-1) + else: + print(deq[-1]) diff --git a/lily/week_4/boj_15828.py b/lily/week_4/boj_15828.py new file mode 100644 index 0000000..88cf788 --- /dev/null +++ b/lily/week_4/boj_15828.py @@ -0,0 +1,44 @@ +""" +패킷은 라우터를 여러 번 거침. +라우터 안의 버퍼: FIFO로 패킷 처리 +라우터가 패킷을 처리하는 속도 < 패킷이 들어오는 속도 => 버퍼에 공간이 생길 때까지 입력받는 패킷은 모두 버려짐 + +입력 +N: 버퍼 크기 +둘째줄~: 라우터가 처리해야 할 정보 +양의 정수: 해당하는 번호의 패킷 +0은: 라우터가 패킷 하나를 처리 +비어있을 때는 0이 입력 X +-1은 입력 끝 + +출력 +라우터에 남아있는 패킷 출력 +비어있으면 empty + +O(N) +10만 * 20만 = 2 * 10^10 => 1초를 벗어남 +""" + +from collections import deque + +buffer_size = int(input()) +buffer = deque() + +while True: + pack = int(input()) + if pack == -1: + break + + if pack == 0: + buffer.popleft() + continue + + if len(buffer) >= buffer_size: + continue + + buffer.append(pack) + +if len(buffer) > 0: + print(*buffer) +else: + print("empty") \ No newline at end of file diff --git a/lily/week_4/boj_1874.py b/lily/week_4/boj_1874.py new file mode 100644 index 0000000..c1702a9 --- /dev/null +++ b/lily/week_4/boj_1874.py @@ -0,0 +1,24 @@ +N = int(input()) +stack = [] +answer = [] +current = 0 +is_seq_possible = True +for _ in range(N): + target_num = int(input()) - 1 + + while current <= target_num: + stack.append(current) + answer.append("+") + current += 1 + + if len(stack) > 0 and stack[-1] == target_num: + stack.pop() + answer.append("-") + else: + is_seq_possible = False + break + +if is_seq_possible: + print('\n'.join(answer)) +else: + print("NO") \ No newline at end of file diff --git a/lily/week_4/boj_4949.py b/lily/week_4/boj_4949.py new file mode 100644 index 0000000..5b50551 --- /dev/null +++ b/lily/week_4/boj_4949.py @@ -0,0 +1,38 @@ +""" +소괄호, 대괄호 짝 이루는지 확인 +""" + +import sys + +readline = sys.stdin.readline +while True: + sentence = readline().rstrip() + if sentence == ".": + break + + brackets = [] + is_balanced = True + for word in sentence: + if word not in ["(", ")", "[", "]"]: + continue + + if word in ["(", "["]: + brackets.append(word) + elif word == ")": + if len(brackets) == 0 or brackets[-1] != "(": + is_balanced = False + break + brackets.pop() + else: + if len(brackets) == 0 or brackets[-1] != "[": + is_balanced = False + break + brackets.pop() + + if len(brackets) > 0: + is_balanced = False + + if is_balanced: + print("yes") + else: + print("no") diff --git a/lily/week_4/boj_5397.py b/lily/week_4/boj_5397.py new file mode 100644 index 0000000..a575fd2 --- /dev/null +++ b/lily/week_4/boj_5397.py @@ -0,0 +1,27 @@ +import sys + +def parsing_password(inputs): + cursor_idx = 0 + password = [] + for char in inputs: + if char == '<': + cursor_idx = max(cursor_idx - 1, 0) + elif char == '>': + cursor_idx = min(cursor_idx + 1, len(password)) + elif char == '-': + cursor_idx = max(cursor_idx - 1, 0) + if cursor_idx == 0: + continue + else: + password.pop(cursor_idx) + else: + password.insert(cursor_idx, char) + cursor_idx += 1 + + return ''.join(password) + +readline = sys.stdin.readline +T = int(readline()) +for _ in range(T): + answer = parsing_password(readline().rstrip()) + print(answer) \ No newline at end of file diff --git a/lily/week_4/boj_5430.py b/lily/week_4/boj_5430.py new file mode 100644 index 0000000..73b80c5 --- /dev/null +++ b/lily/week_4/boj_5430.py @@ -0,0 +1,59 @@ +""" +R: 뒤집기 +D: 첫번째 수 버리기 -> 배열이 있는 경우 에러 + +입력 +첫째줄 테스트 케이스 개수 +둘째줄부터 함수 p 리스트 e.g. RDD +배열의 길이 n +배열에 들어있는 수 + +출력 +각 테스트 케이스에 대해 함수를 수행한 결과를 출력 +에러가 발생한 경우 error 출력 +""" + +import sys +from collections import deque + +readline = sys.stdin.readline +T = int(readline()) + +for _ in range(T): + actions = list(readline().rstrip()) + nums_len = int(readline()) + nums_input = readline() + if nums_len == 0: + if len([action for action in actions if action == "D"]) > 0: + print("error") + else: + print("[]") + continue + + deq = deque(list(map(int, nums_input[1:-2].split(",")))) + is_left = True + is_error = False + for action in actions: + if action == 'R': + is_left = not is_left + else: + if len(deq) == 0: + is_error = True + break + + if is_left: + deq.popleft() + else: + deq.pop() + + if is_error: + print("error") + else: + if is_left: + output = ",".join(list(map(str, deq))) + print(f"[{output}]") + else: + output = ",".join(list(map(str, list(deq)[::-1]))) + print(f"[{output}]") + + \ No newline at end of file diff --git a/lily/week_5/boj_11779.py b/lily/week_5/boj_11779.py new file mode 100644 index 0000000..3489563 --- /dev/null +++ b/lily/week_5/boj_11779.py @@ -0,0 +1,49 @@ +""" +heapq에 넣을 때 해당 노드까지의 리스트도 업데이트 +깊은 복사 + edge 돌아가면서 리스트에 요소 append + +출력 +1. 최소 비용 +2. 최소 비용에 속해있는 도시의 수 +3. 최소 비용에 속해있는 도시 (순서대로, 시작과 도착 노드 포함) + +디버깅한 것 +시작 노드에서의 dist는 0 +""" + +import sys +import heapq +import copy +readline = sys.stdin.readline +n = int(readline()) # 노드의 수 +m = int(readline()) # 간선의 수 + +edges = [[] for _ in range(n+1)] # 특정 노드에서 갈 수 있는 간선 정보를 저장하는 (node, cost) 튜플 리스트 +for _ in range(m): + s, e, c = map(int, readline().split()) + edges[s].append((e, c)) + +start, end = map(int, readline().split()) # 최종 출발점, 도착점 +dist = [float('inf') for _ in range(n+1)] +path = [[] for _ in range(n+1)] # 시작점에서 해당 노드까지 갔을 때의 경로 +hq = [] +hq.append((0, start)) +dist[start] = 0 +path[start].append(start) + +while len(hq) > 0: + now_cost, now = heapq.heappop(hq) + if dist[now] < now_cost: continue + + for edge in edges[now]: + e, c = edge + new_cost = now_cost + c + if dist[e] > new_cost: + dist[e] = new_cost + heapq.heappush(hq, (new_cost, e)) + path[e] = copy.deepcopy(path[now]) + path[e].append(e) + +print(dist[end]) +print(len(path[end])) +print(*path[end]) \ No newline at end of file diff --git a/lily/week_5/boj_1238.py b/lily/week_5/boj_1238.py new file mode 100644 index 0000000..f5bb890 --- /dev/null +++ b/lily/week_5/boj_1238.py @@ -0,0 +1,61 @@ +""" +- 문제 요약 +N명의 학생들이 X번 마을에 모임. +해당 마을에 갔다가, 되돌아 와야 하는데 총 비용이 가장 큰 경우를 찾아라. +(s -> e, e -> s 따로 구해서 그 합이 가장 큰 값을 찾아야 함) + + +- 입력 +학생 수 N, 간선 수 M, 특정 마을 X +M개 만큼 s, e, c + +- 출력 +갔다 오는데 가장 오래 걸리는 시간 + +- 각 s 지점에서 X까지 걸리는 시간 각각 계산 +- 특정 마을 X에서 가는 시간도 계산 + +놓쳤던 부분: 파티가 진행되는 곳에 사는 학생의 dist는 0으로 만들어야 함. +""" + +import sys +import heapq + +def dijkstra(start, X, edges): # 시작 지점부터 끝 지점 + dist = [float('inf') for _ in range(N+1)] + if start == X: + dist[X] = 0 + hq = [] + heapq.heappush(hq, (0, start)) + + while len(hq) > 0: + now_cost, now = heapq.heappop(hq) + if dist[now] < now_cost: + continue + + for edge in edges[now]: + e, c = edge + new_dist = now_cost + c + if dist[e] > new_dist: + dist[e] = new_dist + heapq.heappush(hq, (new_dist, e)) + + return dist + +readline = sys.stdin.readline +N, M, X = map(int, readline().split()) # 학생, 간선, 도착지 +edges = [[] for _ in range(N+1)] +for _ in range(M): + s, e, c = map(int, readline().split()) + edges[s].append((e, c)) + +# 도착 지점 -> 각 노드 +dist_from_start = dijkstra(X, X, edges) + +# 각 노드 -> 도착 지점 +answer = -1 +for s in range(1, N+1): + dist_to_end = dijkstra(s, X, edges) + answer = max(answer, dist_from_start[s] + dist_to_end[X]) + +print(answer) \ No newline at end of file diff --git a/lily/week_5/boj_1916.py b/lily/week_5/boj_1916.py new file mode 100644 index 0000000..bd7bd79 --- /dev/null +++ b/lily/week_5/boj_1916.py @@ -0,0 +1,38 @@ +""" +입력 +도시의 개수 N +버스의 개수 M +M개의 버스 정부 s, e, c +s -> e까지 가는 최소 비용 출력 +""" +import sys +import heapq + +readline = sys.stdin.readline + +N = int(readline()) +M = int(readline()) + +edges = [[] for _ in range(N+1)] # 각 노드가 갈 수 있는 정점과 비용 +distance = [float('inf')] * (N+1) # 시작 노드에서 각 노드까지의 거리 + +for _ in range(M): + s, e, c = map(int, readline().split()) + edges[s].append((e, c)) + +start, end = map(int, readline().split()) +hq = [] +hq.append((0, start)) + +while len(hq) > 0: + now_cost, now = heapq.heappop(hq) + if distance[now] < now_cost: # 이미 적은 가중치로 갱신되었음. + continue + for edge in edges[now]: + e, cost = map(int, edge) + new_cost = now_cost + cost + if distance[e] > new_cost: + distance[e] = new_cost + heapq.heappush(hq, (new_cost, e)) + +print(distance[end]) \ No newline at end of file diff --git a/lily/week_6/answer.py b/lily/week_6/answer.py new file mode 100644 index 0000000..dce3fc5 --- /dev/null +++ b/lily/week_6/answer.py @@ -0,0 +1,39 @@ +""" +노드 번호 중 가장 큰 번호를 찾는다. +노드 정점 별로 들어오는 간선 수, 나가는 간선 수를 계산한다. +그래프 개수를 찾을 때는, 각자 대표되는 점을 기준으로 개수를 센다. (도넛 모양은 대표되는 점이 없기 때문에 소거법으로 구함) +1. 나가는 간선 수가 0개다 => 막대 모양 +2. 나가는 간선 수가 2개 이상, 들어오는 간선 수도 2개 이상 => 8자 모양 +3. 나가는 간선 수가 2개 이상, 들어오는 간선 수는 0개 => 추가된 정점 +1~3의 케이스에 해당하지 않는다면 패스 + +추가된 정점에서 나가는 간선의 개수 (즉, 그래프의 개수)에서 막대 모양 개수와 8자 모양 개수를 제외하면 도넛 모양 +""" + +def solution(edges): + out_in_edges = {} # 각 노드 별로 나가는 간선 수, 들어오는 간선 수 계산 + + for edge in edges: + s, e = edge + if not out_in_edges.get(s): + out_in_edges[s] = [0, 0] + if not out_in_edges.get(e): + out_in_edges[e] = [0, 0] + + out_in_edges[s][0] += 1 # 나가는 간선 수 추가 + out_in_edges[e][1] += 1 # 들어오는 간선 수 추가 + + added_node = graph_1_cnt = graph_2_cnt = graph_3_cnt = 0 + + for node, cnts in out_in_edges.items(): + out_cnt, in_cnt = cnts + if out_cnt == 0: + graph_2_cnt += 1 + elif out_cnt >= 2 and in_cnt == 0: + added_node = node + elif out_cnt == 2 and in_cnt >= 2: + graph_3_cnt += 1 + + graph_1_cnt = out_in_edges[added_node][0] - graph_2_cnt - graph_3_cnt + print([added_node, graph_1_cnt, graph_2_cnt, graph_3_cnt]) + diff --git a/lily/week_6/boj_11053.py b/lily/week_6/boj_11053.py new file mode 100644 index 0000000..04677ae --- /dev/null +++ b/lily/week_6/boj_11053.py @@ -0,0 +1,16 @@ +import sys + +readline = sys.stdin.readline +N = int(readline()) +seq = list(map(int, readline().split())) +dp = [1] * N # i번째 수를 마지막으로 가지는 부분 증가 수열의 길이 +answer = 0 + +for i in range(N): + max_len = 0 + for j in range(i+1): + if seq[i] > seq[j]: # 특정 값보다 크다는 것은 특정 값에서의 수열의 마지막에 붙일 수 있다는 의미 + dp[i] = max(dp[i], dp[j] + 1) + answer = max(answer, dp[i]) + +print(answer) diff --git a/lily/week_6/boj_12865.py b/lily/week_6/boj_12865.py new file mode 100644 index 0000000..ec0adc2 --- /dev/null +++ b/lily/week_6/boj_12865.py @@ -0,0 +1,26 @@ +import sys + +readline = sys.stdin.readline + +N, K = map(int, readline().split()) # 물품 수, 배낭 무게 +jewels = [(0, 0)] # 각 물품의 무게, 가치 튜플 리스트 + +for _ in range(N): + w, v = map(int, readline().split()) + jewels.append((w, v)) + +dp = [[0 for _ in range(K+1)] for _ in range(N+1)] # 각 물건 별로 각 무게 (1~K) 까지의 최댓값 + +for i in range(1, N+1): + for j in range(1, K+1): + w, v = jewels[i] + + if w > j: + dp[i][j] = dp[i-1][j] + continue + + dp[i][j] = max(dp[i-1][j], v + dp[i-1][j-w]) + +print(dp[N][K]) + + diff --git a/lily/week_6/boj_9251.py b/lily/week_6/boj_9251.py new file mode 100644 index 0000000..ca20acc --- /dev/null +++ b/lily/week_6/boj_9251.py @@ -0,0 +1,17 @@ +first_seq = [0] + list(input()) +second_seq = [0] + list(input()) + +N = len(first_seq) +M = len(second_seq) +dp = [[0 for _ in range(M)] for _ in range(N)] + +for i in range(1, N): + for j in range(1, M): + if first_seq[i] == second_seq[j]: + dp[i][j] = dp[i-1][j-1] + 1 + continue + + # 일치하지 않으면 first_seq[i] 또는 second_seq[j] 중 하나는 제외 + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + +print(dp[N-1][M-1]) \ No newline at end of file diff --git a/lily/week_6/boj_9252.py b/lily/week_6/boj_9252.py new file mode 100644 index 0000000..18b24f5 --- /dev/null +++ b/lily/week_6/boj_9252.py @@ -0,0 +1,38 @@ +from collections import deque + +first_seq = [0] + list(input()) +second_seq = [0] + list(input()) + +N = len(first_seq) +M = len(second_seq) +dp = [[(0, 0) for _ in range(M)] for _ in range(N)] # 튜플 리스트 (값, 어디에서 왔는지 - 0, 1, 2 (i-1, j-1, 일치)) + +for i in range(1, N): + for j in range(1, M): + if first_seq[i] == second_seq[j]: + dp[i][j] = (dp[i-1][j-1][0] + 1, 2) + continue + + # 일치하지 않으면 first_seq[i] 또는 second_seq[j] 중 하나는 제외 + if dp[i-1][j] > dp[i][j-1]: + dp[i][j] = (dp[i-1][j][0], 0) + else: + dp[i][j] = (dp[i][j-1][0], 1) + +print(dp[N-1][M-1][0]) + +# 역추적 +answer = deque() +i, j = N - 1, M - 1 +while i > 0 and j > 0: + origin = dp[i][j][1] + if origin == 2: + answer.appendleft(first_seq[i]) + i -= 1 + j -= 1 + elif origin == 1: + j -= 1 + else: + i -= 1 + +print(''.join(answer)) \ No newline at end of file diff --git a/lily/week_after/boj_1012.py b/lily/week_after/boj_1012.py new file mode 100644 index 0000000..f528e40 --- /dev/null +++ b/lily/week_after/boj_1012.py @@ -0,0 +1,57 @@ +from collections import deque +import sys + +readline = sys.stdin.readline + +dx = [-1, 0, 1, 0] +dy = [0, 1, 0, -1] + +def bfs(x, y): + global visited + visited[x][y] = True + dq = deque() + dq.append((x, y)) + + if board[x][y] == 'o': + a += 1 + elif board[x][y] == 'v': + b += 1 + + while dq: + tmp_x, tmp_y = dq.popleft() + + for i in range(4): + new_x = tmp_x + dx[i] + new_y = tmp_y + dy[i] + if new_x >= 0 and new_x < R and new_y >= 0 and new_y < C and board[new_x][new_y] != '#' and not visited[new_x][new_y]: + visited[new_x][new_y] = True + dq.append((new_x, new_y)) + if board[new_x][new_y] == 'o': + a += 1 + elif board[new_x][new_y] == 'v': + b += 1 + + if a == 0 and b == 0: + return 0, 0 + elif a > b: + return a, 0 + else: + return 0, b + +R, C = map(int, readline().split()) +board = [[] for _ in range(R)] +for i in range(R): + arr = list(readline().rstrip()) + board[i] = arr + +visited = [[False for _ in range(C)] for _ in range(R)] + +s_cnt = 0 +w_cnt = 0 + +for i in range(R): + for j in range(C): + if board[i][j] != '#' and not visited[i][j]: + bfs(i, j) + +print(f"{s_cnt} {w_cnt}") \ No newline at end of file diff --git a/lily/week_after/boj_1068.py b/lily/week_after/boj_1068.py new file mode 100644 index 0000000..9e27033 --- /dev/null +++ b/lily/week_after/boj_1068.py @@ -0,0 +1,31 @@ +import sys + +sys.setrecursionlimit(10**6) +readline = sys.stdin.readline + +def dfs(node): + global answer + if node == X: + return + + if not edges[node] or edges[node] == [X]: # 리프노드 + answer += 1 + return + + for end_node in edges[node]: + dfs(end_node) + +N = int(readline()) # 노드의 개수 +edges = [[] for _ in range(N)] # 자식 노드의 수 +arr = list(map(int, readline().split())) # 각 노드의 부모 +X = int(readline()) # 지울 노드 번호 +start = -1 +for j in range(len(arr)): + if arr[j] == -1: + start = j + continue + edges[arr[j]].append(j) + +answer = 0 +dfs(start) +print(answer) \ No newline at end of file diff --git a/lily/week_after/boj_1072.py b/lily/week_after/boj_1072.py new file mode 100644 index 0000000..2b92474 --- /dev/null +++ b/lily/week_after/boj_1072.py @@ -0,0 +1,63 @@ +# import sys + +# readline = sys.stdin.readline + +# X, Y = map(int, readline().split()) +# if X == Y: +# print(-1) +# exit() + +# rate = int((Y*100)/X) + +# left = 1 +# right = X +# is_change = False +# answer = -1 +# while left <= right: +# mid = (left + right) // 2 # 게임을 더 하는 횟수 +# tmp_X = X + mid +# tmp_Y = Y + mid +# tmp_rate = int((tmp_Y*100)/tmp_X) +# if tmp_rate > rate: +# answer = mid +# right = mid - 1 +# else: +# left = mid + 1 + +# print(answer) + + +import sys +from decimal import Decimal + +readline = sys.stdin.readline + +X, Y = map(int, readline().split()) +if X == Y: + print(-1) + exit() + +rate = int((Y*100)/X) + +left = 1 +right = X +is_change = False +while left <= right: + mid = (left + right) // 2 # 게임을 더 하는 횟수 + tmp_X = X + mid + tmp_Y = Y + mid + tmp_rate = int((tmp_Y*100)/tmp_X) + if tmp_rate == rate: + left = mid + 1 + else: + is_change = True + right = mid - 1 + +if not is_change: + print(-1) +else: + left_rate = int(((Y+left)*100)/(X+left)) + if rate != left_rate: + print(left) + else: + print(right) diff --git a/lily/week_after/boj_10815.py b/lily/week_after/boj_10815.py new file mode 100644 index 0000000..d7142da --- /dev/null +++ b/lily/week_after/boj_10815.py @@ -0,0 +1,29 @@ +import sys +import bisect + +# 방법 1. 이분 탐색 +readline = sys.stdin.readline +N = int(input()) +arr = sorted(map(int, readline().split())) +M = int(input()) +brr = list(map(int, readline().split())) + +for b in brr: + idx = bisect.bisect_left(arr, b) + if idx < N and arr[idx] == b: + print(1, end=" ") + else: + print(0, end=" ") + +# 방법 2. set +readline = sys.stdin.readline +N = int(input()) +arr = set(map(int, readline().split())) +M = int(input()) +brr = list(map(int, readline().split())) + +for b in brr: + if b in arr: + print(1, end=" ") + else: + print(0, end=" ") \ No newline at end of file diff --git a/lily/week_after/boj_10826.py b/lily/week_after/boj_10826.py new file mode 100644 index 0000000..1338672 --- /dev/null +++ b/lily/week_after/boj_10826.py @@ -0,0 +1,13 @@ +N = int(input()) + +if N == 0: + print(0) +elif N == 1: + print(1) +else: + dp = [0] * (N+1) + dp[1] = 1 + for i in range(2, N+1): + dp[i] = dp[i-1] + dp[i-2] + + print(dp[N]) \ No newline at end of file diff --git a/lily/week_after/boj_1149.py b/lily/week_after/boj_1149.py new file mode 100644 index 0000000..c3bf6db --- /dev/null +++ b/lily/week_after/boj_1149.py @@ -0,0 +1,16 @@ +import sys + +readline = sys.stdin.readline + +N = int(readline()) +cost = [[0, 0, 0] for _ in range(N+1)] +dp = [[float('inf'), float('inf'), float('inf')] for _ in range(N+1)] +dp[0] = [0, 0, 0] + +for i in range(1, N+1): + cost[i] = list(map(int, readline().split())) + dp[i][0] = min(dp[i-1][1], dp[i-1][2]) + cost[i][0] + dp[i][1] = min(dp[i-1][0], dp[i-1][2]) + cost[i][1] + dp[i][2] = min(dp[i-1][0], dp[i-1][1]) + cost[i][2] + +print(min(dp[N])) diff --git a/lily/week_after/boj_1389.py b/lily/week_after/boj_1389.py new file mode 100644 index 0000000..e69448e --- /dev/null +++ b/lily/week_after/boj_1389.py @@ -0,0 +1,83 @@ +import sys +from collections import deque + +readline = sys.stdin.readline + +N, M = map(int, readline().split()) # 유저 수, 관계 수 +edges = [[] for _ in range(N+1)] + +def bfs(start): + dist = [-1] * (N+1) + dist[start] = 0 + dq = deque() + dq.append((start, 0)) + + while dq: + now_node, now_cost = dq.popleft() + + for end_node in edges[now_node]: + if dist[end_node] == -1: + dq.append((end_node, now_cost+1)) + dist[end_node] = now_cost+1 + + return sum(dist[1:]) + +for _ in range(M): + a, b = map(int, readline().split()) + edges[a].append(b) + edges[b].append(a) + +min_dist = float('inf') +answer_node = -1 +for i in range(1, N+1): + kevin_dist = bfs(i) + if kevin_dist < min_dist: + min_dist = kevin_dist + answer_node = i + +print(answer_node) + +"""다익스트라 풀이 +import sys +import heapq + +readline = sys.stdin.readline + +N, M = map(int, readline().split()) # 유저 수, 관계 수 +edges = [[] for _ in range(N+1)] + +def calculate_kevin_dist(start): + dist = [float('inf')] * (N+1) + dist[start] = 0 + hq = [] + heapq.heappush(hq, (0, start)) + + while hq: + now_cost, now_node = heapq.heappop(hq) + if dist[now_node] < now_cost: + continue + + for edge in edges[now_node]: + end_node, weight = edge + new_cost = now_cost + weight + if dist[end_node] > new_cost: + dist[end_node] = new_cost + heapq.heappush(hq, (new_cost, end_node)) + + return sum(dist[1:]) + +for _ in range(M): + a, b = map(int, readline().split()) + edges[a].append((b, 1)) + edges[b].append((a, 1)) + +min_dist = float('inf') +answer_node = -1 +for i in range(1, N+1): + kevin_dist = calculate_kevin_dist(i) + if kevin_dist < min_dist: + min_dist = kevin_dist + answer_node = i + +print(answer_node) +""" diff --git a/lily/week_after/boj_1504.py b/lily/week_after/boj_1504.py new file mode 100644 index 0000000..a75cb26 --- /dev/null +++ b/lily/week_after/boj_1504.py @@ -0,0 +1,46 @@ +import sys +import heapq + +readline = sys.stdin.readline + +N, E = map(int, readline().split()) # 정점 수, 간선 수 +edges = [[] for _ in range(N+1)] + +def dijkstra(s, e): + dist = [float('inf')] * (N+1) + dist[s] = 0 + hq = [] + heapq.heappush(hq, (0, s)) + + while hq: + now_cost, now_node = heapq.heappop(hq) + if dist[now_node] < now_cost: continue + + for edge in edges[now_node]: + end_node, weight = edge + new_cost = now_cost + weight + if dist[end_node] > new_cost: + dist[end_node] = new_cost + heapq.heappush(hq, (new_cost, end_node)) + + return dist[e] + + + +for _ in range(E): + a, b, w = map(int, readline().split()) + edges[a].append((b, w)) + edges[b].append((a, w)) + +V1, V2 = map(int, readline().split()) # 시작, 끝 +# 1 -> V2 -> V1 -> N +# 1에서의 최단 경로, v1에서의 최단 경로, v2에서의 최단 경로 +answer1 = dijkstra(1, V2) + dijkstra(V2, V1) + dijkstra(V1, N) +answer2 = dijkstra(1, V1) + dijkstra(V1, V2) + dijkstra(V2, N) + +answer = min(answer1, answer2) + +if answer == float('inf'): + print(-1) +else: + print(answer) diff --git a/lily/week_after/boj_1753.py b/lily/week_after/boj_1753.py new file mode 100644 index 0000000..c99c396 --- /dev/null +++ b/lily/week_after/boj_1753.py @@ -0,0 +1,39 @@ +import sys +import heapq + +readline = sys.stdin.readline +V, E = map(int, readline().split()) # 정점, 간선 개수 +K = int(readline().rstrip()) # 시작 정점 +edges = [[] for _ in range(V+1)] +dist = [float('inf')] * (V+1) + +def dijkstra(): + dist[K] = 0 + hq = [] + heapq.heappush(hq, (0, K)) + + while hq: + now_cost, now_node = heapq.heappop(hq) + + if dist[now_node] < now_cost: + continue + + for edge in edges[now_node]: + end_node, weight = edge + new_cost = now_cost + weight + if dist[end_node] > new_cost: + heapq.heappush(hq, (new_cost, end_node)) + dist[end_node] = new_cost + +for _ in range(E): + s, e, w = map(int, readline().split()) + edges[s].append((e, w)) + + +dijkstra() + +for v in range(1, V+1): + if dist[v] == float('inf'): + print("INF") + else: + print(dist[v]) diff --git a/lily/week_after/boj_1916.py b/lily/week_after/boj_1916.py new file mode 100644 index 0000000..dcbe3c2 --- /dev/null +++ b/lily/week_after/boj_1916.py @@ -0,0 +1,36 @@ +import sys +import heapq + +readline = sys.stdin.readline + +N = int(readline()) # 도시 개수 +M = int(readline()) # 버스 개수 +dist = [float('inf')] * (N+1) +edges = [[] for _ in range(N+1)] # 각 노드가 갈 수 있는 간선 (간선, 비용) + +def dijkstra(start): + global dist + dist[start] = 0 + hq = [] + heapq.heappush(hq, (0, start)) + + while len(hq) > 0: + now_cost, now_node = heapq.heappop(hq) + + if dist[now_node] < now_cost: + continue + + for edge in edges[now_node]: + end_node, cost = edge + new_cost = now_cost + cost + if dist[end_node] > new_cost: + dist[end_node] = new_cost + heapq.heappush(hq, (new_cost, end_node)) + +for _ in range(M): + s, e, c = map(int, readline().split()) # 출발 도시, 도착 도시, 비용 + edges[s].append((e, c)) + +S, E = map(int, readline().split()) # 최종 시작, 도착 도시 +dijkstra(S) +print(dist[E]) # 출발 도시에서 도착 도시까지 가는데 드는 최소 비용 \ No newline at end of file diff --git a/lily/week_after/boj_21736.py b/lily/week_after/boj_21736.py new file mode 100644 index 0000000..35e510e --- /dev/null +++ b/lily/week_after/boj_21736.py @@ -0,0 +1,40 @@ +import sys +from collections import deque + +def bfs(start_x, start_y): + dx = [-1, 0, 1, 0] + dy = [0, 1, 0, -1] + visited = [[False for _ in range(M)] for _ in range(N)] + cnt = 0 + visited[start_x][start_y] = True + q = deque() + q.append((start_x, start_y)) + + while len(q) > 0: + x, y = q.pop() + if board[x][y] == 'P': + cnt += 1 + + for i in range(4): + new_x = x + dx[i] + new_y = y + dy[i] + if 0 <= new_x < N and 0 <= new_y < M and not visited[new_x][new_y] and board[new_x][new_y] != 'X': + q.append((new_x, new_y)) + visited[new_x][new_y] = True + + return cnt + +readline = sys.stdin.readline +N, M = map(int, readline().split()) +board = [[] for _ in range(N)] +start_x, start_y = 0, 0 +for i in range(N): + board[i] = list(map(str, readline().rstrip())) + if 'I' in board[i]: + start_x = i + start_y = board[i].index('I') +answer = bfs(start_x, start_y) +if answer == 0: + print('TT') +else: + print(answer) \ No newline at end of file diff --git a/lily/week_after/boj_2178.py b/lily/week_after/boj_2178.py new file mode 100644 index 0000000..86e631b --- /dev/null +++ b/lily/week_after/boj_2178.py @@ -0,0 +1,39 @@ +import sys +from collections import deque + +readline = sys.stdin.readline + +def bfs(start_x, start_y): + visited = [[False for _ in range(M+1)] for _ in range(N+1)] + visited[start_x][start_y] = True + dx = [-1, 0, 1, 0] + dy = [0, -1, 0, 1] + dq = deque([]) + dq.append((start_x, start_y, 1)) + + while dq: + x, y, d = dq.popleft() # 튜플을 언팩 + + if x == N and y == M: + return d + + for i in range(4): + new_x = x + dx[i] + new_y = y + dy[i] + if 1 <= new_x <= N and 1 <= new_y <= M and board[new_x][new_y] == 1 and not visited[new_x][new_y]: + dq.append((new_x, new_y, d+1)) + visited[new_x][new_y] = True + +N, M = map(int, readline().split()) # 도착 지점 +board = [[] for _ in range(N+1)] + +for i in range(1, N+1): + board[i] = [0] + list(map(int, readline().rstrip())) + +answer = bfs(1, 1) +print(answer) + +# (1, 1)에서 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수 출력 +# 인접한 칸으로만 이동할 수 있음. +# bfs +# 거리는 시작, 도착 위치 포함 diff --git a/lily/week_after/boj_2343.py b/lily/week_after/boj_2343.py new file mode 100644 index 0000000..7dda9c4 --- /dev/null +++ b/lily/week_after/boj_2343.py @@ -0,0 +1,30 @@ +import sys + +readline = sys.stdin.readline +N, M = map(int, readline().split()) +arr = list(map(int, readline().split())) + +left = max(arr) +right = sum(arr) + +answer = right + +while left <= right: + mid = (left + right) // 2 + total = 0 + count = 1 + + for length in arr: + if total + length > mid: # 현재 블루레이에 더 이상 담을 수 없는 경우 + count += 1 # 새로운 블루레이 필요 + total = length # 새 블루레이에 현재 강의 추가 + else: + total += length # 현재 블루레이에 강의 추가 + + if count <= M: + answer = mid + right = mid - 1 + else: + left = mid + 1 + +print(answer) diff --git a/lily/week_after/boj_2512.py b/lily/week_after/boj_2512.py new file mode 100644 index 0000000..9e342af --- /dev/null +++ b/lily/week_after/boj_2512.py @@ -0,0 +1,28 @@ +import sys + +readline = sys.stdin.readline +N = int(input()) +arr = list(map(int, readline().split())) # 각자 필요한 금액 +M = int(input()) # 예산액 + +def calculate_sum(max_value): + return sum(min(a, max_value) for a in arr) + +if sum(arr) <= M: + print(max(arr)) + exit() + +left = 1 +right = max(arr) +answer = -1 # 최대 상한액 +while left <= right: + mid = (left + right) // 2 # 임시 상한액 + if calculate_sum(mid) > M: + right = mid - 1 + else: + answer = mid + left = mid + 1 + +print(answer) + + diff --git a/lily/week_after/boj_2606.py b/lily/week_after/boj_2606.py new file mode 100644 index 0000000..1acf420 --- /dev/null +++ b/lily/week_after/boj_2606.py @@ -0,0 +1,32 @@ +import sys +from collections import deque + +readline = sys.stdin.readline + +def bfs(start): + visited = [False] * (N+1) + visited[start] = True + answer = 0 + q = deque() + q.append(start) + + while q: + now_node = q.popleft() + for end_node in edges[now_node]: + if not visited[end_node]: + visited[end_node] = True + q.append(end_node) + answer += 1 + + return answer + + +N = int(readline()) # 컴퓨터 수 +edges = [[] for _ in range(N+1)] +M = int(readline()) # 컴퓨터 쌍의 수 +for _ in range(M): + a, b = map(int, readline().split()) # 양방향 + edges[a].append(b) + edges[b].append(a) + +print(bfs(1)) # 1번 컴퓨터가 바이러스에 걸렸을 때, 바이러스에 걸리는 컴퓨터 수 (1번 제외) \ No newline at end of file diff --git a/lily/week_after/boj_30804.py b/lily/week_after/boj_30804.py new file mode 100644 index 0000000..41203ca --- /dev/null +++ b/lily/week_after/boj_30804.py @@ -0,0 +1,44 @@ +import sys + +readline = sys.stdin.readline + +N = int(readline()) # 과일의 개수 +fruits = list(map(int, readline().split())) +dic = {} # 각 과일에 대한 개수 +# for f in fruits: +# if f in dic: +# dic[f] += 1 +# else: +# dic[f] = 1 + +left, right = 0, 0 +f = fruits[0] +dic[f] = 1 +""" +left~right까지의 과일 개수가 2개 이하라면 right를 늘리고 +아니면 left를 줄임 +=> 끝까지 탐색 +""" + +answer = 0 + +while right < N: + if len(dic) <= 2: + answer = max(answer, right-left+1) + right += 1 + if right == N: + break + + f = fruits[right] + if dic.get(f): + dic[f] += 1 + else: + dic[f] = 1 + else: + f = fruits[left] + dic[f] -= 1 + if dic[f] == 0: + del dic[f] + left += 1 + +print(answer) \ No newline at end of file diff --git a/lily/week_after/boj_3184.py b/lily/week_after/boj_3184.py new file mode 100644 index 0000000..7d75a92 --- /dev/null +++ b/lily/week_after/boj_3184.py @@ -0,0 +1,62 @@ +from collections import deque +import sys + +readline = sys.stdin.readline + +dx = [-1, 0, 1, 0] +dy = [0, 1, 0, -1] + +def bfs(x, y): + global visited + visited[x][y] = True + dq = deque() + dq.append((x, y)) + + a = 0 + b = 0 + + if board[x][y] == 'o': + a += 1 + elif board[x][y] == 'v': + b += 1 + + while dq: + tmp_x, tmp_y = dq.popleft() + + for i in range(4): + new_x = tmp_x + dx[i] + new_y = tmp_y + dy[i] + if new_x >= 0 and new_x < R and new_y >= 0 and new_y < C and board[new_x][new_y] != '#' and not visited[new_x][new_y]: + visited[new_x][new_y] = True + dq.append((new_x, new_y)) + if board[new_x][new_y] == 'o': + a += 1 + elif board[new_x][new_y] == 'v': + b += 1 + + if a == 0 and b == 0: + return 0, 0 + elif a > b: + return a, 0 + else: + return 0, b + +R, C = map(int, readline().split()) +board = [[] for _ in range(R)] +for i in range(R): + arr = list(readline().rstrip()) + board[i] = arr + +visited = [[False for _ in range(C)] for _ in range(R)] + +s_cnt = 0 +w_cnt = 0 + +for i in range(R): + for j in range(C): + if board[i][j] != '#' and not visited[i][j]: + tmp_s_cnt, tmp_w_cnt = bfs(i, j) + s_cnt += tmp_s_cnt + w_cnt += tmp_w_cnt + +print(f"{s_cnt} {w_cnt}") \ No newline at end of file diff --git a/lily/week_after/boj_32399.py b/lily/week_after/boj_32399.py new file mode 100644 index 0000000..9edeb63 --- /dev/null +++ b/lily/week_after/boj_32399.py @@ -0,0 +1,15 @@ + +input_str = input() + +if input_str == "1)(": + print(1) +elif input_str == ")1(": + print(2) +elif input_str == "(1)": + print(0) +elif input_str == ")(1": + print(1) +elif input_str == "()1": + print(1) +elif input_str == "1()": + print(1) \ No newline at end of file diff --git a/lily/week_after/boj_32400.py b/lily/week_after/boj_32400.py new file mode 100644 index 0000000..e704656 --- /dev/null +++ b/lily/week_after/boj_32400.py @@ -0,0 +1,25 @@ +import sys + +scores = list(map(int, sys.stdin.readline().split())) + +bob_sum = sum(scores) +alice_sum = 0 +idx = scores.index(20) +# 20이 맨왼쪽인 경우 +if idx == 0: + alice_sum += scores[idx] + scores[idx+1] + scores[-1] +# 20이 맨 오른쪽인 경우 +elif idx == len(scores) - 1: + alice_sum += scores[idx] + scores[idx-1] + scores[0] +else: + alice_sum += scores[idx] + scores[idx-1] + scores[idx+1] + +bob_avg = bob_sum/20 +alice_avg = alice_sum/3 + +if bob_avg < alice_avg: + print("Alice") +elif bob_avg > alice_avg: + print("Bob") +else: + print("Tie") \ No newline at end of file diff --git a/lily/week_after/boj_32401.py b/lily/week_after/boj_32401.py new file mode 100644 index 0000000..1235010 --- /dev/null +++ b/lily/week_after/boj_32401.py @@ -0,0 +1,25 @@ +N = int(input()) +arr = list(map(str, input())) +answer = 0 + +def check_answer(str_list): + return 'N' in str_list and str_list.count('N') == 1 + +a_index_list = [] +for i, s in enumerate(arr): + if s == "A": + a_index_list.append(i) + +if len(a_index_list) <= 1: + print(0) + exit() + +s = a_index_list[0] +for a_idx in range(1, len(a_index_list)): + e = a_index_list[a_idx] + sub_arr = arr[s:e] + if check_answer(sub_arr): + answer += 1 + s = e + +print(answer) diff --git a/lily/week_after/boj_32402.py b/lily/week_after/boj_32402.py new file mode 100644 index 0000000..27302cd --- /dev/null +++ b/lily/week_after/boj_32402.py @@ -0,0 +1,95 @@ +""" +W: 앞으로 1만큼 이동 +A: 왼쪽으로 1 이동 +S: 뒤로 1만큼 이동 +D: 오른쪽으로 1만큼 이동 + +MR: 오른쪽 회전 +ML: 왼쪽 회전 + +출력: +주인공과 카메라의 위치 +""" + +def rotate_dir(now_dir, dir): + if now_dir == "U": + if dir == "MR": + return "R", (-1, 1) + elif dir == "ML": + return "L", (1, 1) + + elif now_dir == "R": + if dir == "MR": + return "D", (1, 1) + elif dir == "ML": + return "U", (1, -1) + + elif now_dir == "D": + if dir == "MR": + return "L", (1, -1) + elif dir == "ML": + return "R", (-1, -1) + + elif now_dir == "L": + if dir == "MR": + return "U", (-1, -1) + elif dir == "ML": + return "D", (-1, 1) + + +def get_move(now_dir, dir): + if now_dir == "U": + if dir == "W": + return (0, 1) + elif dir == "A": + return (-1, 0) + elif dir == "S": + return (0, -1) + elif dir == "D": + return (1, 0) + + elif now_dir == "R": + if dir == "W": + return (1, 0) + elif dir == "A": + return (0, 1) + elif dir == "S": + return (-1, 0) + elif dir == "D": + return (0, -1) + + elif now_dir == "D": + if dir == "W": + return (0, -1) + elif dir == "A": + return (1, 0) + elif dir == "S": + return (0, 1) + elif dir == "D": + return (-1, 0) + + elif now_dir == "L": + if dir == "W": + return (-1, 0) + elif dir == "A": + return (0, -1) + elif dir == "S": + return (1, 0) + elif dir == "D": + return (0, 1) + +main = (0, 0) # 주인공의 위치 +camera = (0, -1) # 카메라의 위치 +now_dir = "U" # 시점의 방향 - U, R, D, L + +input_len = int(input()) +for _ in range(input_len): + dir = input() + if dir not in ["MR", "ML"]: + next_position = get_move(now_dir, dir) + main = (main[0] + next_position[0], main[1] + next_position[1]) + camera = (camera[0] + next_position[0], camera[1] + next_position[1]) + else: + now_dir, next_camera_position = rotate_dir(now_dir, dir) + camera = (camera[0] + next_camera_position[0], camera[1] + next_camera_position[1]) + print(f"{main[0]} {main[1]} {camera[0]} {camera[1]}") \ No newline at end of file diff --git a/lily/week_after/boj_6236.py b/lily/week_after/boj_6236.py new file mode 100644 index 0000000..d19c16b --- /dev/null +++ b/lily/week_after/boj_6236.py @@ -0,0 +1,38 @@ +import sys + +readline = sys.stdin.readline + +N, M = map(int, readline().split()) # 기간, 인출 횟수 +costs = [] # N일 동안의 지출 내역 +for _ in range(N): + cost = int(readline()) + costs.append(cost) + +left = max(costs) +right = sum(costs) + +def check_can(mid): # 문제의 조건을 만족하는지 판단하는 함수 + """ + 남은 금액이 그날 사용할 금액보다 많더라도 남은 금액은 통장에 집어넣고 다시 K원을 인출할 수 있다 + => 인출 횟수가 M보다 작거나 같으면 됨. + """ + cnt = 1 # 통장 인출 횟수 + left_money = mid + for cost in costs: + if left_money < cost: + cnt += 1 + left_money = mid + + left_money -= cost + return cnt <= M + +K = 0 # 인출해야 할 최소 금액 +while left <= right: + mid = (left + right) // 2 + if check_can(mid): + K = mid + right = mid - 1 + else: + left = mid + 1 + +print(K) \ No newline at end of file diff --git a/lily/week_after/test.py b/lily/week_after/test.py new file mode 100644 index 0000000..24921f1 --- /dev/null +++ b/lily/week_after/test.py @@ -0,0 +1,43 @@ +import sys +from collections import deque + +# o == 빈 공간 +# X == 벽 +# I == 도연 +# P == 사람 + +def dfs(x,y): + global count + visited[x][y] = True + + if graph[x][y] == 'P': + count += 1 + + for i in range(4): + nx = x + dx[i] + ny = y + dy[i] + + # 캠퍼스 밖으로 벗어나지 않고, 방문했던 위치가 아니며, 벽이 아닌 경우에만 이동 + if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny] and graph[nx][ny] != 'X': + dfs(nx,ny) + +input = sys.stdin.readline +N, M = map(int, input().strip().split()) + +dx = [-1, 0, 1, 0] +dy = [0, 1, 0, -1] + +count = 0 + +graph = list(input() for _ in range(N)) +visited = [[False]*M for _ in range(N)] + +for i in range(N): + for j in range(M): + if graph[i][j] == 'I': + dfs(i,j) + +if count == 0: + print('TT') +else: + print(count) \ No newline at end of file diff --git a/lily/week_after/toss_1.py b/lily/week_after/toss_1.py new file mode 100644 index 0000000..5e1891c --- /dev/null +++ b/lily/week_after/toss_1.py @@ -0,0 +1,9 @@ +import sys + +s = sys.stdin.readline().rstrip() +answer = -1 +for i in range(0, len(s) - 2): + if s[i] == s[i+1] and s[i] == s[i+2]: + answer = max(answer, int(s[i:i+3])) + +print(answer) \ No newline at end of file diff --git a/lily/week_after/toss_2.py b/lily/week_after/toss_2.py new file mode 100644 index 0000000..35d92f3 --- /dev/null +++ b/lily/week_after/toss_2.py @@ -0,0 +1,63 @@ +import sys + +input_assets = eval(sys.stdin.readline()) + +checked_assets = [] # 중복 및 validation한 자산 모음 +validated_assets = [] # 유효한 자산 모음 + +def validate_assets(re_year, asset_code, re_month, re_order): + return validate_re_year(re_year) and validate_asset_code(asset_code) and validate_re_month(int(re_year), re_month) and validate_re_order(re_order) + +def validate_re_year(re_year): + return len(re_year) == 2 and 13 <= int(re_year) <= 22 + +def validate_asset_code(asset_code): + return asset_code in ['SP', 'KE', 'MO', 'CO', 'DE'] + +def validate_re_month(re_year, re_month): + if re_year == 13: + return re_month in ['04', '05', '06', '07', '08', '09', '10', '11', '12'] + elif 14 <= re_year <= 21: + return re_month in ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] + else: + return re_month in ['01', '02', '03', '04', '05', '06', '07', '08'] + +def validate_re_order(re_order): + if len(re_order) == 2 and re_order.isdigit(): + re_order_int = int(re_order) + return 1 <= re_order_int <= 99 + return False + +for asset in input_assets: + if asset in checked_assets: + continue + + checked_assets.append(asset) + + ## validation + if len(asset) != 9: + continue + + parts = asset.split("-") + if len(parts) != 2 or len(parts[1]) != 6: + continue + + re_year = parts[0] # 등록 연도 + asset_code = parts[1][0:2] # 취급 자산 코드 + re_month = parts[1][2:4] # 등록 월 + re_order = parts[1][4:6] # 등록 순서 + + if validate_assets(re_year, asset_code, re_month, re_order): + validated_assets.append(asset) + +asset_code_priority = { + "SP": 1, + "KE": 2, + "MO": 3, + "CO": 4, + "DE": 5 +} + +sorted_assets = sorted(validated_assets, key=lambda x: (int(x.split("-")[0]), asset_code_priority[x.split("-")[1][0:2]], int(x.split("-")[1][2:4]), int(x.split("-")[1][4:6]))) + +print(sorted_assets) diff --git a/lily/week_after/toss_3.py b/lily/week_after/toss_3.py new file mode 100644 index 0000000..d9ff7b0 --- /dev/null +++ b/lily/week_after/toss_3.py @@ -0,0 +1,57 @@ +import sys +from collections import deque + +""" +조직 ID,조직명,상위 조직 ID,소속 팀원 수\n1,토스팀,,1\n2,인터널 트라이브,1,1\n,3,인터널 매니저 팀,2,7\n4,비바 플랫폼 팀,2,14\n5,아웃터널 트라이브,1,2\n6,가이드 팀,5,4\n7,피트아웃 사일로,5,11 +""" + +def bfs(start_team_id): + cnt = 0 + visited[start_team_id] = True + dq = deque() + dq.append(start_team_id) + + while len(dq) > 0: + now_team_id = dq.pop() + cnt += team_infos[now_team_id][2] # 팀원 수 누적 + + for sub_team_id in edges[now_team_id]: + if not visited[sub_team_id]: + visited[sub_team_id] = True + dq.append(sub_team_id) + + return cnt + +readline = sys.stdin.readline +csv_string = "조직 ID,조직명,상위 조직 ID,소속 팀원 수\n1,토스팀,,1\n2,인터널 트라이브,1,1\n3,인터널 매니저 팀,2,7\n4,비바 플랫폼 팀,2,14\n5,아웃터널 트라이브,1,2\n6,가이드 팀,5,4\n7,피트아웃 사일로,5,11".rstrip() +keyword = "아웃" +orgs = csv_string.split('\n') +target_team_ids = [] # keyword가 포함되어 있는 팀 id 리스트 +team_len = len(orgs) +edges = [[] for _ in range(team_len+1)] # 각 노드에서 갈 수 있는 간선들 +team_infos = [[] for _ in range(team_len+1)] # (팀 id, 이름, 팀원 수) + +for i in range(1, team_len): + infos = orgs[i].split(",") + # print(infos) + team_id = int(infos[0]) + team_name = infos[1] + team_num = int(infos[3]) + team_infos[i] = (team_id, team_name, team_num) + + if infos[2] != '': + supervise_id = int(infos[2]) + edges[supervise_id].append(team_id) # 상위 조직의 간선에 추가 + + if keyword in team_name: + target_team_ids.append(team_id) + + +answer = 0 +visited = [False] * (team_len+1) +for target_team_id in target_team_ids: + if visited[target_team_id]: + continue + + answer += bfs(target_team_id) +print(answer) \ No newline at end of file