diff --git a/.vs/Haedal_AlgorithmStudy/v17/.wsuo b/.vs/Haedal_AlgorithmStudy/v17/.wsuo new file mode 100644 index 0000000..6129296 Binary files /dev/null and b/.vs/Haedal_AlgorithmStudy/v17/.wsuo differ diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite new file mode 100644 index 0000000..a67645e Binary files /dev/null and b/.vs/slnx.sqlite differ diff --git a/HHNAM/11to20/11.py b/HHNAM/11to20/11.py new file mode 100644 index 0000000..f286663 --- /dev/null +++ b/HHNAM/11to20/11.py @@ -0,0 +1,11 @@ +def solution(s): + stack = [ ] + for c in s: + if stack and stack[-1] == c: + stack.pop( ) + else: + stack.append(c) + return int(not stack) + +# print(solution('baabaa')) +# print(solution('cdcd')) \ No newline at end of file diff --git a/HHNAM/11to20/12.py b/HHNAM/11to20/12.py new file mode 100644 index 0000000..53042ab --- /dev/null +++ b/HHNAM/11to20/12.py @@ -0,0 +1,16 @@ +def solution(prices): + n = len(prices) + answer = [0] * n + + stack = [0] + for i in range(1, n): + while stack and prices[i] < prices[stack[-1]]: + j = stack.pop( ) + answer[j] = i - j + stack.append(i) + while stack: + j = stack.pop( ) + answer[j] = n - 1 - j + return answer + +# print(solution([1,2,4,2,3])) \ No newline at end of file diff --git a/HHNAM/11to20/13.py b/HHNAM/11to20/13.py new file mode 100644 index 0000000..b6986e8 --- /dev/null +++ b/HHNAM/11to20/13.py @@ -0,0 +1,27 @@ +def solution(board, moves): + lanes = [[ ] for _ in range(len(board[0]))] + + for i in range(len(board) - 1, -1, -1): + for j in range(len(board[0])): + if board[i][j]: + lanes[j].append(board[i][j]) + + bucket = [ ] + + answer = 0 + + for m in moves: + if lanes[m - 1]: + doll = lanes[m - 1].pop( ) + + if bucket and bucket[-1] == doll: + bucket.pop( ) + answer += 2 + else: + bucket.append(doll) + + return answer + +# board = [[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] +# moves = [1,5,3,5,1,2,1,4] +# print(solution(board, moves)) \ No newline at end of file diff --git a/HHNAM/11to20/14.py b/HHNAM/11to20/14.py new file mode 100644 index 0000000..7cc4cc7 --- /dev/null +++ b/HHNAM/11to20/14.py @@ -0,0 +1,39 @@ +def solution(n, k, cmd): + deleted = [ ] + + up = [i - 1 for i in range(n + 2)] + + down = [i + 1 for i in range(n + 1)] + + k += 1 + + for cmd_i in cmd: + if cmd_i.startswith("C"): + deleted.append(k) + up[down[k]] = up[k] + down[up[k]] = down[k] + k = up[k] if n < down[k] else down[k] + + elif cmd_i.startswith("Z"): + restore = deleted.pop( ) + down[up[restore]] = restore + up[down[restore]] = restore + + else: + action, num = cmd_i.split( ) + if action == "U": + for _ in range(int(num)): + k = up[k] + else: + for _ in range(int(num)): + k = down[k] + + answer = ["O"] * n + for i in deleted: + answer[i - 1] = "X" + return "".join(answer) + +# n = 8 +# k = 2 +# cmd = ['D 2', 'C', 'U 3', 'C', 'D 4', 'C', 'U 2', 'Z', 'Z'] +# print(solution(n,k,cmd)) \ No newline at end of file diff --git a/HHNAM/11to20/15.py b/HHNAM/11to20/15.py new file mode 100644 index 0000000..da2d5f6 --- /dev/null +++ b/HHNAM/11to20/15.py @@ -0,0 +1,12 @@ +from collections import deque + +def solution(N, K): + queue = deque(range(1, N+1)) + + while len(queue) > 1: + for _ in range(K-1): + queue.append(queue.popleft()) + queue.popleft() + return queue[0] + +# print(solution(5,2)) \ No newline at end of file diff --git a/HHNAM/11to20/16.py b/HHNAM/11to20/16.py new file mode 100644 index 0000000..21015f1 --- /dev/null +++ b/HHNAM/11to20/16.py @@ -0,0 +1,24 @@ +import math + +def solution(progresses, speeds): + answer = [ ] + n = len(progresses) + days_left = [math.ceil((100 - progresses[i]) / speeds[i]) for i in range(n)] + + count = 0 + max_day = days_left[0] + + for i in range(n): + if days_left[i] <= max_day: + count += 1 + else: + answer.append(count) + count = 1 + max_day = days_left[i] + + answer.append(count) + return answer + +# progresses = [93,30,55] +# speeds = [1,30,5] +# print(solution(progresses, speeds)) \ No newline at end of file diff --git a/HHNAM/11to20/17.py b/HHNAM/11to20/17.py new file mode 100644 index 0000000..91125d4 --- /dev/null +++ b/HHNAM/11to20/17.py @@ -0,0 +1,23 @@ +from collections import deque + +def solution(cards1, cards2, goal): + cards1 = deque(cards1) + cards2 = deque(cards2) + goal = deque(goal) + + while goal: + if cards1 and cards1[0] == goal[0]: + cards1.popleft() + goal.popleft() + elif cards2 and cards2[0] == goal[0]: + cards2.popleft() + goal.popleft() + else: + break + + return "Yes" if not goal else "No" + +# cards1 = ['i', 'drink', 'water'] +# cards2 = ['want', 'to'] +# goal = ['i', 'want', 'to', 'drink', 'water'] +# print(solution(cards1, cards2, goal)) diff --git a/HHNAM/11to20/18.py b/HHNAM/11to20/18.py new file mode 100644 index 0000000..b2edf94 --- /dev/null +++ b/HHNAM/11to20/18.py @@ -0,0 +1,24 @@ +def count_sort(arr, k): + hashtable = [0] * (k + 1) + + for num in arr: + if num <= k: + hashtable[num] = 1 + return hashtable + +def solution(arr, target): + hashtable = count_sort(arr, target) + + for num in arr: + complement = target - num + if ( + complement != num + and complement >= 0 + and complement <= target + and hashtable[complement] == 1 + ): + return True + return False + +# print(solution([1, 2, 3, 4, 8], 6)) +# print(solution([2, 3, 5, 9], 10)) \ No newline at end of file diff --git a/HHNAM/11to20/19.py b/HHNAM/11to20/19.py new file mode 100644 index 0000000..95716a0 --- /dev/null +++ b/HHNAM/11to20/19.py @@ -0,0 +1,21 @@ +def polynomial_hash(str): + p = 31 + m = 1_000_000_007 + hash_value = 0 + for char in str: + hash_value = (hash_value * p + ord(char)) % m + return hash_value + +def solution(string_list, query_list): + hash_list = [polynomial_hash(str) for str in string_list] + + result = [ ] + for query in query_list: + query_hash = polynomial_hash(query) + if query_hash in hash_list: + result.append(True) + else: + result.append(False) + return result + +# print(solution(["apple", "banana", "cherry"], ["banana", "kiwi", "melon", "apple"] )) \ No newline at end of file diff --git a/HHNAM/11to20/20.py b/HHNAM/11to20/20.py new file mode 100644 index 0000000..3683fdd --- /dev/null +++ b/HHNAM/11to20/20.py @@ -0,0 +1,19 @@ +def solution(participant, completion): + dic = { } + + for p in participant: + if p in dic: + dic[p] += 1 + else: + dic[p] = 1 + + for c in completion: + dic[c] -= 1 + + for key in dic.keys( ) : + if dic[key] > 0: + return key + +# participant = ['leo', 'kiki', 'eden'] +# completion = ['eden', 'kiki'] +# print(solution(participant, completion)) \ No newline at end of file diff --git a/HHNAM/1to10/10.py b/HHNAM/1to10/10.py new file mode 100644 index 0000000..bf11963 --- /dev/null +++ b/HHNAM/1to10/10.py @@ -0,0 +1,31 @@ +def solution(s): + answer = 0 + n = len(s) + for i in range(n): + stack = [ ] + for j in range(n): + c = s[(i + j) % n] + if c == "(" or c == "[" or c == "{": + stack.append(c) + else: + if not stack: + break + + if c == ")" and stack[-1] == "(": + stack.pop( ) + elif c == "]" and stack[-1] == "[": + stack.pop( ) + elif c == "}" and stack[-1] == "{": + stack.pop( ) + else: + break + else: + if not stack: + answer += 1 + return answer + + +# print(solution('[](){}')) +# print(solution('}]()[{')) +# print(solution('[)(]')) +# print(solution('}}}')) \ No newline at end of file diff --git a/HHNAM/1to10/4.py b/HHNAM/1to10/4.py index 873ed44..70e0189 100644 --- a/HHNAM/1to10/4.py +++ b/HHNAM/1to10/4.py @@ -19,5 +19,5 @@ def solution(answers): highest_scores.append(i+1) return highest_scores -print(solution([1,2,3,4,5])) -print(solution([1,3,2,4,2])) +# print(solution([1,2,3,4,5])) +# print(solution([1,3,2,4,2])) diff --git a/HHNAM/1to10/5.py b/HHNAM/1to10/5.py new file mode 100644 index 0000000..dbad7e4 --- /dev/null +++ b/HHNAM/1to10/5.py @@ -0,0 +1,15 @@ +def solution(arr1, arr2): + r1, c1 = len(arr1), len(arr1[0]) + r2, c2 = len(arr2), len(arr2[0]) + + ret = [[0] * c2 for _ in range(r1)] + + for i in range(r1): + for j in range(c2): + for k in range(c1): + ret[i][j] += arr1[i][k] * arr2[k][j] + return ret + +# arr1 = [[1,4],[3,2],[4,1]] +# arr2 = [[3,3],[3,3]] +# print(solution(arr1, arr2)) \ No newline at end of file diff --git a/HHNAM/1to10/6.py b/HHNAM/1to10/6.py new file mode 100644 index 0000000..52f9470 --- /dev/null +++ b/HHNAM/1to10/6.py @@ -0,0 +1,22 @@ +def solution(N, stages): + challenger = [0] * (N + 2) + for stage in stages: + challenger[stage] += 1 + + fails = { } + total = len(stages) + + for i in range(1, N + 1): + if challenger[i] == 0 : + fails[i] = 0 + else: + fails[i] = challenger[i] / total + total -= challenger[i] + + result = sorted(fails, key=lambda x : fails[x], reverse=True) + + return result + +N = 5 +stages = [2,1,2,6,2,4,3,3] +print(solution(N, stages)) \ No newline at end of file diff --git a/HHNAM/1to10/7.py b/HHNAM/1to10/7.py new file mode 100644 index 0000000..4a091e5 --- /dev/null +++ b/HHNAM/1to10/7.py @@ -0,0 +1,28 @@ +def is_valid_move(nx, ny) : + return 0 <= nx < 11 and 0 <= ny < 11 + +def update_location(x, y, dir) : + if dir == 'U': + nx, ny = x, y + 1 + elif dir == 'D': + nx, ny = x, y - 1 + elif dir == 'L': + nx, ny = x - 1, y + elif dir == 'R': + nx, ny = x + 1, y + return nx, ny + +def solution(dirs): + x, y = 5, 5 + ans = set( ) + for dir in dirs : + nx, ny = update_location(x, y, dir) + if not is_valid_move(nx, ny) : + continue + ans.add((x, y, nx, ny)) + ans.add((nx, ny, x, y)) + x, y = nx, ny + return len(ans)/2 + +# dirs = 'ULURRDLLU' +# print(solution(dirs)) \ No newline at end of file diff --git a/HHNAM/1to10/8.py b/HHNAM/1to10/8.py new file mode 100644 index 0000000..481679d --- /dev/null +++ b/HHNAM/1to10/8.py @@ -0,0 +1,18 @@ +def solution(s): + stack = [ ] + for c in s: + if c == "(": + stack.append(c) + elif c == ")": + if not stack: + return False + else: + stack.pop( ) + if stack: + return False + else: + return True + + +# print(solution('(())()')) +# print(solution('((())()')) \ No newline at end of file diff --git a/HHNAM/1to10/9.py b/HHNAM/1to10/9.py new file mode 100644 index 0000000..d552b2c --- /dev/null +++ b/HHNAM/1to10/9.py @@ -0,0 +1,13 @@ +def solution(decimal): + stack = [] + while decimal > 0: + remainder = decimal % 2 + stack.append(str(remainder)) + decimal //= 2 + stack.reverse() + return ''.join(stack) + + +# print(solution(10)) +# print(solution(27)) +# print(solution(12345)) \ No newline at end of file diff --git a/HHNAM/21to30/21.py b/HHNAM/21to30/21.py new file mode 100644 index 0000000..362a73e --- /dev/null +++ b/HHNAM/21to30/21.py @@ -0,0 +1,18 @@ +def solution(want, number, discount): + want_dict = { } + for i in range(len(want)): + want_dict[want[i]] = number[i] + + answer = 0 + + for i in range(len(discount) - 9): + discount_10d = { } + + for j in range(i, i + 10): + if discount[j] in want_dict: + discount_10d[discount[j]] = discount_10d.get(discount[j], 0) + 1 + + if discount_10d == want_dict: + answer += 1 + + return answer diff --git a/HHNAM/21to30/22.py b/HHNAM/21to30/22.py new file mode 100644 index 0000000..20a3449 --- /dev/null +++ b/HHNAM/21to30/22.py @@ -0,0 +1,16 @@ +def solution(record): + answer = [ ] + uid = { } + for line in record: + cmd = line.split(" ") + if cmd[0] != "Leave": + uid[cmd[1]] = cmd[2] + for line in record: + cmd = line.split(" ") + if cmd[0] == "Enter": + answer.append("%s님이 들어왔습니다." % uid[cmd[1]]) + elif cmd[0] == "Change": + pass + else: + answer.append("%s님이 나갔습니다." % uid[cmd[1]]) + return answer diff --git a/HHNAM/21to30/23.py b/HHNAM/21to30/23.py new file mode 100644 index 0000000..f1355ca --- /dev/null +++ b/HHNAM/21to30/23.py @@ -0,0 +1,21 @@ +def solution(genres, plays): + answer = [ ] + genres_dict = { } + play_dict = { } + + for i in range(len(genres)): + genre = genres[i] + play = plays[i] + if genre not in genres_dict: + genres_dict[genre] = [ ] + play_dict[genre] = 0 + genres_dict[genre].append((i, play)) + play_dict[genre] += play + + sorted_genres = sorted(play_dict.items( ) , key=lambda x: x[1], reverse=True) + + for genre, _ in sorted_genres: + sorted_songs = sorted(genres_dict[genre], key=lambda x: (-x[1], x[0])) + answer.extend([idx for idx, _ in sorted_songs[:2]]) + + return answer \ No newline at end of file diff --git a/HHNAM/21to30/24.py b/HHNAM/21to30/24.py new file mode 100644 index 0000000..d68edc7 --- /dev/null +++ b/HHNAM/21to30/24.py @@ -0,0 +1,22 @@ +def solution(id_list, report, k): + reported_user = { } + count = { } + for r in report: + user_id, reported_id = r.split( ) + if reported_id not in reported_user: + reported_user[reported_id] = set( ) + reported_user[reported_id].add(user_id) + for reported_id, user_id_lst in reported_user.items( ) : + if len(user_id_lst) >= k: + for uid in user_id_lst: + if uid not in count: + count[uid] = 1 + else: + count[uid] += 1 + answer = [ ] + for i in range(len(id_list)): + if id_list[i] not in count: + answer.append(0) + else: + answer.append(count[id_list[i]]) + return answer \ No newline at end of file diff --git a/HHNAM/21to30/25.py b/HHNAM/21to30/25.py new file mode 100644 index 0000000..d20aad6 --- /dev/null +++ b/HHNAM/21to30/25.py @@ -0,0 +1,19 @@ +from itertools import combinations +from collections import Counter + +def solution(orders, course): + answer = [ ] + + for c in course: + menu = [ ] + for order in orders: + comb = combinations(sorted(order), c) + menu += comb + + counter = Counter(menu) + if (len(counter) != 0 and max(counter.values( ) ) != 1): + for m, cnt in counter.items( ) : + if cnt == max(counter.values( ) ): + answer.append("".join(m)) + + return sorted(answer) \ No newline at end of file diff --git a/HHNAM/21to30/26.py b/HHNAM/21to30/26.py new file mode 100644 index 0000000..f087689 --- /dev/null +++ b/HHNAM/21to30/26.py @@ -0,0 +1,33 @@ +def preorder(nodes, idx): + if idx < len(nodes): + ret = str(nodes[idx]) + " " + ret += preorder(nodes, idx * 2 + 1) + ret += preorder(nodes, idx * 2 + 2) + return ret + else: + return "" + +def inorder(nodes, idx): + if idx < len(nodes): + ret = inorder(nodes, idx * 2 + 1) + ret += str(nodes[idx]) + " " + ret += inorder(nodes, idx * 2 + 2) + return ret + else: + return "" + +def postorder(nodes, idx): + if idx < len(nodes): + ret = postorder(nodes, idx * 2 + 1) + ret += postorder(nodes, idx * 2 + 2) + ret += str(nodes[idx]) + " " + return ret + else: + return "" + +def solution(nodes): + return [ + preorder(nodes,0)[:-1], + inorder(nodes,0)[:-1], + postorder(nodes,0)[:-1], + ] \ No newline at end of file diff --git a/HHNAM/21to30/27.py b/HHNAM/21to30/27.py new file mode 100644 index 0000000..8ad58e2 --- /dev/null +++ b/HHNAM/21to30/27.py @@ -0,0 +1,50 @@ +class Node: + def __init__(self, key): + self.left = None + self.right = None + self.val = key + +class BST: + def __init__(self): + self.root = None + def insert(self, key): + if not self.root: + self.root = Node(key) + else: + curr = self.root + while True: + if key < curr.val: + if curr.left: + curr = curr.left + else: + curr.left = Node(key) + break + else: + if curr.right: + curr = curr.right + else: + curr.right = Node(key) + break + def search(self, key): + curr = self.root + while curr and curr.val != key: + if key < curr.val: + curr = curr.left + else: + curr = curr.right + return curr +def solution(lst, search_lst): + bst = BST() + for key in lst: + bst.insert(key) + result = [] + for search_val in search_lst: + if bst.search(search_val): + result.append(True) + else: + result.append(False) + return result + + +# print(solution([5, 3, 8, 4, 2, 1, 7, 10], [1, 2, 5, 6])) # [True, True, True, False] +# print(solution([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])) # [False, False, False, False, False] \ No newline at end of file diff --git a/HHNAM/21to30/28.py b/HHNAM/21to30/28.py new file mode 100644 index 0000000..c52c5eb --- /dev/null +++ b/HHNAM/21to30/28.py @@ -0,0 +1,7 @@ +def solution(n, a, b): + answer = 0 + while a != b: + a = (a + 1) // 2 + b = (b + 1) // 2 + answer += 1 + return answer \ No newline at end of file diff --git a/HHNAM/21to30/29.py b/HHNAM/21to30/29.py new file mode 100644 index 0000000..0bf0d45 --- /dev/null +++ b/HHNAM/21to30/29.py @@ -0,0 +1,14 @@ +def solution(enroll, referral, seller, amount): + parent = dict(zip(enroll, referral)) + + total = {name: 0 for name in enroll} + + for i in range(len(seller)): + money = amount[i] * 100 + cur_name = seller[i] + while money > 0 and cur_name != "-": + total[cur_name] += money - money // 10 + cur_name = parent[cur_name] + money //= 10 + + return [total[name] for name in enroll] \ No newline at end of file diff --git a/HHNAM/21to30/30.py b/HHNAM/21to30/30.py new file mode 100644 index 0000000..5fe2f4e --- /dev/null +++ b/HHNAM/21to30/30.py @@ -0,0 +1,43 @@ +from collections import deque + +def is_valid_move(ny, nx, n, m, maps): + return 0 <= ny < n and 0 <= nx < m and maps[ny][nx] != "X" + +def append_to_queue(ny, nx, k, time, visited, q): + if not visited[ny][nx][k]: + visited[ny][nx][k] = True + q.append((ny, nx, k, time + 1)) + +def solution(maps): + n, m = len(maps), len(maps[0]) + visited = [[[False for _ in range(2)] for _ in range(m)] for _ in range(n)] + dy = [-1, 1, 0, 0] + dx = [0, 0, -1, 1] + q = deque( ) + end_y, end_x = -1, -1 + + for i in range(n): + for j in range(m): + if maps[i][j] == "S": + q.append((i, j, 0, 0)) + visited[i][j][0] = True + if maps[i][j] == "E": + end_y, end_x = i, j + + while q: + y, x, k, time = q.popleft( ) + + if y == end_y and x == end_x and k == 1: + return time + + for i in range(4): + ny, nx = y + dy[i], x + dx[i] + if not is_valid_move(ny, nx, n, m, maps): + continue + + if maps[ny][nx] == "L": + append_to_queue(ny, nx, 1, time, visited, q) + else: + append_to_queue(ny, nx, k, time, visited, q) + + return -1 \ No newline at end of file diff --git a/HHNAM/31to40/31.py b/HHNAM/31to40/31.py new file mode 100644 index 0000000..4f4bcf9 --- /dev/null +++ b/HHNAM/31to40/31.py @@ -0,0 +1,30 @@ +from collections import deque + +def solution(info, edges): + def build_tree(info, edges): + tree = [[] for _ in range(len(info))] + for edge in edges: + tree[edge[0]].append(edge[1]) + return tree + + tree = build_tree(info, edges) + max_sheep = 0 + + q = deque([(0, 1,0, set())]) + + while q: + current, sheep_count, wolf_count, visited = q.popleft() + max_sheep = max(max_sheep, sheep_count) + visited.update(tree[current]) + + for next_node in visited: + if info[next_node]: + if sheep_count != wolf_count + 1: + q.append( + (next_node, sheep_count, wolf_count + 1, visited - {next_node}) + ) + else: + q.append( + (next_node, sheep_count + 1, wolf_count, visited - {next_node}) + ) + return max_sheep \ No newline at end of file diff --git a/HHNAM/31to40/32.py b/HHNAM/31to40/32.py new file mode 100644 index 0000000..48c5a07 --- /dev/null +++ b/HHNAM/31to40/32.py @@ -0,0 +1,69 @@ +from collections import deque + +class Node: + def __init__(self, info, num, left=None, right=None): + self.info = info + self.left = left + self.right = right + self.num = num + + def has_left(self): + return self.left is not None + + def has_right(self): + return self.right is not None + +def make_BT(nodeinfo): + nodes = [i for i in range(1, len(nodeinfo) + 1)] + nodes.sort(key=lambda x: (nodeinfo[x - 1][1], -nodeinfo[x - 1][0]), reverse=True) + root = None + for i in range(len(nodes)): + if root is None: + root = Node(nodeinfo[nodes[0] - 1], nodes[0]) + else: + parent = root + node = Node(nodeinfo[nodes[i] - 1], nodes[i]) + while True: + if node.info[0] < parent.info[0]: + if parent.has_left(): + parent = parent.left + continue + parent.left = node + break + else: + if parent.has_right(): + parent = parent.right + continue + parent.right = node + break + return root + +def pre_order(root, answer): + stack = [root] + while stack: + node = stack.pop() + if node is None: + continue + answer[0].append(node.num) + stack.append(node.right) + stack.append(node.left) + +def post_order(root, answer): + stack = [(root, False)] + while stack: + node, visited = stack.pop() + if node is None: + continue + if visited: + answer[1].append(node.num) + else: + stack.append((node, True)) + stack.append((node.right, False)) + stack.append((node.left, False)) + +def solution(nodeinfo): + answer = [[], []] + root = make_BT(nodeinfo) + pre_order(root, answer) + post_order(root, answer) + return answer \ No newline at end of file diff --git a/HHNAM/31to40/33.py b/HHNAM/31to40/33.py new file mode 100644 index 0000000..b7fede3 --- /dev/null +++ b/HHNAM/31to40/33.py @@ -0,0 +1,30 @@ +def find(parents, x): + if parents[x] == x: + return x + parents[x] = find(parents, parents[x]) + return parents[x] + + +def union(parents, x, y): + root1 = find(parents, x) + root2 = find(parents, y) + + parents[root2] = root1 + +def solution(k, operations): + parents = list(range(k)) + n = k + + for op in operations: + if op[0] == "u": + union(parents, op[1], op[2]) + elif op[0] == "f": + find(parents, op[1]) + + n = len(set(find(parents, i) for i in range(k))) + + return n + + +# print(solution(3,[['u', 0, 1], ['u', 1, 2], ['f', 2]])) +# print(solution(4,[['u', 0, 1], ['u', 2, 3], ['f', 0]])) \ No newline at end of file diff --git a/HHNAM/31to40/34.py b/HHNAM/31to40/34.py new file mode 100644 index 0000000..081377b --- /dev/null +++ b/HHNAM/31to40/34.py @@ -0,0 +1,5 @@ +def solution(nums): + num_set = set(nums) + n = len(nums) + k = n // 2 + return min(k, len(num_set)) \ No newline at end of file diff --git a/HHNAM/31to40/35.py b/HHNAM/31to40/35.py new file mode 100644 index 0000000..36d2507 --- /dev/null +++ b/HHNAM/31to40/35.py @@ -0,0 +1,9 @@ +def solution(n, words): + used_words = set( ) + prev_word = words[0][0] + for i, word in enumerate(words): + if word in used_words or word[0] != prev_word: + return [(i % n) + 1, (i // n) + 1] + used_words.add(word) + prev_word = word[-1] + return [0, 0] \ No newline at end of file diff --git a/HHNAM/31to40/36.py b/HHNAM/31to40/36.py new file mode 100644 index 0000000..00c2ee1 --- /dev/null +++ b/HHNAM/31to40/36.py @@ -0,0 +1,8 @@ +def solution(phone_book): + phone_book.sort( ) + + for i in range(len(phone_book) - 1): + if phone_book[i + 1].startswith(phone_book[i]): + return False + + return True \ No newline at end of file diff --git a/HHNAM/31to40/37.py b/HHNAM/31to40/37.py new file mode 100644 index 0000000..4f263c7 --- /dev/null +++ b/HHNAM/31to40/37.py @@ -0,0 +1,40 @@ +def find(parent, i): + if parent[i] == i: + return i + parent[i] = find(parent, parent[i]) + return parent[i] + +def union(parent, rank, x, y): + xroot = find(parent, x) + yroot = find(parent, y) + + if rank[xroot] < rank[yroot]: + parent[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parent[yroot] = xroot + else: + parent[yroot] = xroot + rank[xroot] += 1 + +def solution(n, costs): + costs.sort(key=lambda x: x[2]) + + parent = [i for i in range(n)] + rank = [0] * n + + min_cost = 0 + edges = 0 + + for edge in costs: + if edges == n - 1: + break + + x = find(parent, edge[0]) + y = find(parent, edge[1]) + + if x != y: + union(parent, rank, x, y) + min_cost += edge[2] + edges += 1 + + return min_cost \ No newline at end of file diff --git a/HHNAM/31to40/38.py b/HHNAM/31to40/38.py new file mode 100644 index 0000000..fb77b9e --- /dev/null +++ b/HHNAM/31to40/38.py @@ -0,0 +1,21 @@ +from collections import defaultdict + +def solution(graph, start): + adj_list = defaultdict(list) + for u, v in graph: + adj_list[u].append(v) + + def dfs(node, visited, result): + visited.add(node) + result.append(node) + for neighbor in adj_list.get(node, []): + if neighbor not in visited: + dfs(neighbor, visited, result) + + visited = set() + result = [] + dfs(start, visited, result) + return result + +# print(solution([['A', 'B'], ['B', 'C'], ['C', 'D'], ['D', 'E']], 'A')) +# print(solution([['A', 'B'], ['A', 'C'], ['B', 'D'], ['B', 'E'], ['C', 'F'], ['E', 'F']], 'A')) \ No newline at end of file diff --git a/HHNAM/31to40/39.py b/HHNAM/31to40/39.py new file mode 100644 index 0000000..624b6bc --- /dev/null +++ b/HHNAM/31to40/39.py @@ -0,0 +1,28 @@ +from collections import defaultdict, deque + +def solution(graph, start): + adj_list = defaultdict(list) + for u, v in graph: + adj_list[u].append(v) + + def bfs(start): + visited = set() + + queue = deque([start]) + visited.add(start) + result.append(start) + + while queue: + node = queue.popleft() + for neighbor in adj_list.get(node, []): + if neighbor not in visited: + queue.append(neighbor) + visited.add(neighbor) + result.append(neighbor) + + result = [] + bfs(start) + return result + +# print(solution([(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (3, 7), (4, 8), (5, 8), (6, 9), (7, 9)],1)) +# print(solution([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)],1)) \ No newline at end of file diff --git a/HHNAM/31to40/40.py b/HHNAM/31to40/40.py new file mode 100644 index 0000000..749d7ca --- /dev/null +++ b/HHNAM/31to40/40.py @@ -0,0 +1,30 @@ +import heapq + +def solution(graph, start): + distances = {node: float("inf") for node in graph} + distances[start] = 0 + queue = [] + heapq.heappush(queue, [distances[start], start]) + paths = {start: [start]} + visited = set() + + while queue: + current_distance, current_node = heapq.heappop(queue) + if current_node in visited: + continue + visited.add(current_node) + + for adjacent_node, weight in graph[current_node].items(): + distance = current_distance + weight + if distance < distances[adjacent_node]: + distances[adjacent_node] = distance + paths[adjacent_node] = paths[current_node] + [adjacent_node] + heapq.heappush(queue, [distance, adjacent_node]) + + sorted_paths = {node: paths[node] for node in sorted(paths)} + + return [distances, sorted_paths] + + +# print(solution({ 'A': {'B': 9, 'C': 3}, 'B': {'A': 5}, 'C': {'B': 1} }, 'A')) +# print(solution({'A': {'B': 1}, 'B': {'C': 5}, 'C': {'D': 1}, 'D': {}}, 'A')) \ No newline at end of file diff --git a/HHNAM/41to50/41.py b/HHNAM/41to50/41.py new file mode 100644 index 0000000..302a2e3 --- /dev/null +++ b/HHNAM/41to50/41.py @@ -0,0 +1,23 @@ +def solution(graph, source): + num_vertices = len(graph) + + distance = [float("inf")] * num_vertices + distance[source] = 0 + + predecessor = [None] * num_vertices + + for temp in range(num_vertices - 1): + for u in range(num_vertices): + for v, weight in graph[u]: + if distance[u] + weight < distance[v]: + distance[v] = distance[u] + weight + predecessor[v] = u + + for u in range(num_vertices): + for v, weight in graph[u]: + if distance[u] + weight < distance[v]: + return [-1] + return [distance, predecessor] + +print(solution([[(1, 4), (2, 3), (4, -6 )], [(3, 5)], [(1, 2)], [(0, 7), (2, 4)],[(2, 2)]],0)) +print(solution([[(1, 5), (2, -1)], [(2, 2)], [(3, -2)], [(0, 2), (1, 6)]],0)) \ No newline at end of file diff --git a/HHNAM/41to50/42.py b/HHNAM/41to50/42.py new file mode 100644 index 0000000..3ca591a --- /dev/null +++ b/HHNAM/41to50/42.py @@ -0,0 +1,35 @@ +from collections import deque + +def solution(maps): + move = [[-1, 0], [0, -1], [0, 1], [1, 0]] + + n = len(maps) + m = len(maps[0]) + + dist = [[-1] * m for _ in range(n)] + + def bfs(start): + q = deque([start]) + dist[start[0]][start[1]] = 1 + + while q: + here = q.popleft() + + for direct in move: + row, column = here[0] + direct[0], here[1] + direct[1] + + if row < 0 or row >= n or column < 0 or column >= m: + continue + + if maps[row][column] == 0: + continue + + if dist[row][column] == -1: + q.append([row, column]) + dist[row][column] = dist[here[0]][here[1]] + 1 + + return dist + + bfs([0, 0]) + + return dist[n - 1][m - 1] \ No newline at end of file diff --git a/HHNAM/41to50/43.py b/HHNAM/41to50/43.py new file mode 100644 index 0000000..54472e2 --- /dev/null +++ b/HHNAM/41to50/43.py @@ -0,0 +1,14 @@ +def dfs(computers, visited, node): + visited[node] = True + for idx, connected in enumerate(computers[node]): + if connected and not visited[idx]: + dfs(computers, visited, idx) + +def solution(n, computers): + answer = 0 + visited = [False] * n + for i in range(n): + if not visited[i]: + dfs(computers, visited, i) + answer += 1 + return answer \ No newline at end of file diff --git a/HHNAM/41to50/44.py b/HHNAM/41to50/44.py new file mode 100644 index 0000000..2524942 --- /dev/null +++ b/HHNAM/41to50/44.py @@ -0,0 +1,23 @@ +import heapq + +def solution(N, road, K): + graph = [[] for _ in range(N + 1)] + distances = [float("inf")] * (N + 1) + distances[1] = 0 + + for a, b, cost in road: + graph[a].append((b, cost)) + graph[b].append((a, cost)) + + heap = [] + heapq.heappush(heap, (0, 1)) + while heap: + dist, node = heapq.heappop(heap) + + for next_node, next_dist in graph[node]: + cost = dist + next_dist + if cost < distances[next_node]: + distances[next_node] = cost + heapq.heappush(heap, (cost, next_node)) + + return sum(1 for dist in distances if dist <= K) \ No newline at end of file diff --git a/HHNAM/41to50/45.py b/HHNAM/41to50/45.py new file mode 100644 index 0000000..f76d5e7 --- /dev/null +++ b/HHNAM/41to50/45.py @@ -0,0 +1,40 @@ +def solution(board): + def is_valid(x, y): + return 0 <= x < N and 0 <= y < N + + def is_blocked(x, y): + return (x, y) == (0, 0) or not is_valid(x, y) or board[x][y] == 1 + + def calculate_cost(direction, prev_direction, cost): + if prev_direction == -1 or (prev_direction - direction) % 2 == 0: + return cost + 100 + else: + return cost + 600 + + def isShouldUpdate(x, y, direction, new_cost): + return visited[x][y][direction] == 0 or visited[x][y][direction] > new_cost + + queue = [(0, 0, -1, 0)] + N = len(board) + directions = [(0, -1), (-1, 0), (0, 1), (1, 0)] + visited = [[[0 for _ in range(4)] for _ in range(N)] for _ in range(N)] + answer = float("inf") + + while queue: + x, y, prev_direction, cost = queue.pop(0) + + for direction, (dx, dy) in enumerate(directions): + new_x, new_y = x + dx, y + dy + + if is_blocked(new_x, new_y): + continue + + new_cost = calculate_cost(direction, prev_direction, cost) + + if (new_x, new_y) == (N - 1, N - 1): + answer = min(answer, new_cost) + elif isShouldUpdate(new_x, new_y, direction, new_cost): + queue.append((new_x, new_y, direction, new_cost)) + visited[new_x][new_y][direction] = new_cost + + return answer \ No newline at end of file diff --git a/HHNAM/41to50/46.py b/HHNAM/41to50/46.py new file mode 100644 index 0000000..adeb4e5 --- /dev/null +++ b/HHNAM/41to50/46.py @@ -0,0 +1,27 @@ +def solution(n, wires): + graph = [[] for _ in range(n + 1)] + for a, b in wires: + graph[a].append(b) + graph[b].append(a) + + def dfs(node, parent): + cnt = 1 + for child in graph[node]: + if child != parent: + cnt += dfs(child, node) + return cnt + + min_diff = float("inf") + for a, b in wires: + graph[a].remove(b) + graph[b].remove(a) + + cnt_a = dfs(a, b) + cnt_b = n - cnt_a + + min_diff = min(min_diff, abs(cnt_a - cnt_b)) + + graph[a].append(b) + graph[b].append(a) + + return min_diff \ No newline at end of file diff --git a/HHNAM/41to50/47.py b/HHNAM/41to50/47.py new file mode 100644 index 0000000..cbbba82 --- /dev/null +++ b/HHNAM/41to50/47.py @@ -0,0 +1,19 @@ +def solution(N): + results = [] + + def backtrack(sum, selected_nums, start): + if sum == 10: + results.append(selected_nums) + return + + for i in range(start, N + 1): + if sum + i <= 10: + backtrack(sum + i, selected_nums + [i], i + 1) + + backtrack(0, [], 1) + return results + + +# print(solution(5)) +# print(solution(2)) +# print(solution(7)) \ No newline at end of file diff --git a/HHNAM/41to50/48.py b/HHNAM/41to50/48.py new file mode 100644 index 0000000..b145e95 --- /dev/null +++ b/HHNAM/41to50/48.py @@ -0,0 +1,54 @@ +def solution(board): + def is_valid(num, row, col): + return not (in_row(num, row) or in_col(num, col) or in_box(num, row, col)) + + def in_row(num, row): + return num in board[row] + + def in_col(num, col): + return num in (board[i][col] for i in range(9)) + + def in_box(num, row, col): + box_row = (row // 3) * 3 + box_col = (col // 3) * 3 + for i in range(box_row, box_row + 3): + for j in range(box_col, box_col + 3): + if board[i][j] == num: + return True + return False + + def find_empty_position(): + for i in range(9): + for j in range(9): + if board[i][j] == 0: + return i, j + return None + + def find_solution(): + empty_pos = find_empty_position() + if not empty_pos: + return True + row, col = empty_pos + for num in range(1, 10): + if is_valid(num, row, col): + board[row][col] = num + if find_solution(): + return True + board[row][col] = 0 + return False + + find_solution() + return board + + +''' +print(solution([[5, 3, 0, 0, 7, 0, 0, 0, 0], + [6, 0, 0, 1, 9, 5, 0, 0, 0], + [0, 9, 8, 0, 0, 0, 0, 6, 0], + [8, 0, 0, 0, 6, 0, 0, 0, 3], + [4, 0, 0, 8, 0, 3, 0, 0, 1], + [7, 0, 0, 0, 2, 0, 0, 0, 6], + [0, 6, 0, 0, 0, 0, 2, 8, 0], + [0, 0, 0, 4, 1, 9, 0, 0, 5], + [0, 0, 0, 0, 8, 0, 0, 7, 9]])) +''' \ No newline at end of file diff --git a/HHNAM/41to50/49.py b/HHNAM/41to50/49.py new file mode 100644 index 0000000..5041762 --- /dev/null +++ b/HHNAM/41to50/49.py @@ -0,0 +1,15 @@ +def dfs(cur_k, cnt, dungeons, visited): + answer_max = cnt + for i in range(len(dungeons)): + if cur_k >= dungeons[i][0] and visited[i] == 0: + visited[i] = 1 + answer_max = max( + answer_max, dfs(cur_k - dungeons[i][1], cnt + 1, dungeons, visited) + ) + visited[i] = 0 + return answer_max + +def solution(k, dungeons): + visited = [0] * len(dungeons) + answer_max = dfs(k, 0, dungeons, visited) + return answer_max \ No newline at end of file diff --git a/HHNAM/41to50/50.py b/HHNAM/41to50/50.py new file mode 100644 index 0000000..4567405 --- /dev/null +++ b/HHNAM/41to50/50.py @@ -0,0 +1,16 @@ +def getAns(n, y, width, diagonal1, diagonal2): + ans = 0 + if y == n: + ans += 1 + else: + for i in range(n): + if width[i] or diagonal1[i + y] or diagonal2[i - y + n]: + continue + width[i] = diagonal1[i + y] = diagonal2[i - y + n] = True + ans += getAns(n, y + 1, width, diagonal1, diagonal2) + width[i] = diagonal1[i + y] = diagonal2[i - y + n] = False + return ans + +def solution(n): + ans = getAns(n, 0, [False] * n, [False] * (n * 2), [False] * (n * 2)) + return ans \ No newline at end of file diff --git a/HHNAM/51to60/51.py b/HHNAM/51to60/51.py new file mode 100644 index 0000000..683cb79 --- /dev/null +++ b/HHNAM/51to60/51.py @@ -0,0 +1,34 @@ +from itertools import combinations_with_replacement +from collections import Counter + +def solution(n, info): + maxdiff, max_comb = 0, {} + + def calculate_score(combi): + score1, score2 = 0, 0 + for i in range(1, 11): + if info[10 - i] < combi.count(i): + score1 += i + elif info[10 - i] > 0: + score2 += i + return score1, score2 + + def calculate_diff(diff, cnt): + nonlocal maxdiff, max_comb + if diff > maxdiff: + max_comb = cnt + maxdiff = diff + + for combi in combinations_with_replacement(range(11), n): + cnt = Counter(combi) + score1, score2 = calculate_score(combi) + diff = score1 - score2 + calculate_diff(diff, cnt) + + if maxdiff > 0: + answer = [0] * 11 + for n in max_comb: + answer[10 - n] = max_comb[n] + return answer + else: + return [-1] \ No newline at end of file diff --git a/HHNAM/51to60/52.py b/HHNAM/51to60/52.py new file mode 100644 index 0000000..5c84cd9 --- /dev/null +++ b/HHNAM/51to60/52.py @@ -0,0 +1,22 @@ +from itertools import permutations + +def solution(n, weak, dist): + length = len(weak) + for i in range(length): + weak.append(weak[i] + n) + + answer = len(dist) + 1 + + for i in range(length): + for friends in permutations(dist, len(dist)): + cnt = 1 + position = weak[i] + friends[cnt - 1] + for j in range(i, i + length): + if position < weak[j]: + cnt += 1 + if cnt > len(dist): + break + position = weak[j] + friends[cnt - 1] + answer = min(answer, cnt) + + return answer if answer <= len(dist) else -1 \ No newline at end of file diff --git a/HHNAM/51to60/53.py b/HHNAM/51to60/53.py new file mode 100644 index 0000000..091adaf --- /dev/null +++ b/HHNAM/51to60/53.py @@ -0,0 +1,38 @@ +def solution(board, aloc, bloc): + ROW, COL = len(board), len(board[0]) + DR, DC = [-1, 0, 1, 0], [0, 1, 0, -1] + + def is_valid_pos(r, c): + return 0 <= r < ROW and 0 <= c < COL + + def recursive_func(alpha_pos, beta_pos, visited, step): + r, c = alpha_pos if step % 2 == 0 else beta_pos + can_move = False + is_opponent_winner = True + win_steps, lose_steps = [], [] + + for i in range(4): + nr, nc = r + DR[i], c + DC[i] + if is_valid_pos(nr, nc) and (nr, nc) not in visited and board[nr][nc]: + can_move = True + if alpha_pos == beta_pos: + return True, step + 1 + + win, steps_left = ( + recursive_func([nr, nc], beta_pos, visited | {(r, c)}, step + 1) + if step % 2 == 0 + else recursive_func( + alpha_pos, [nr, nc], visited | {(r, c)}, step + 1 + ) + ) + is_opponent_winner &= win + (win_steps if win else lose_steps).append(steps_left) + + if not can_move: + return False, step + if is_opponent_winner: + return False, max(win_steps) + return True, min(lose_steps) + + _, steps = recursive_func(aloc, bloc, set(), 0) + return steps \ No newline at end of file diff --git a/HHNAM/51to60/54.py b/HHNAM/51to60/54.py new file mode 100644 index 0000000..d7cd536 --- /dev/null +++ b/HHNAM/51to60/54.py @@ -0,0 +1,15 @@ +def solution(s): + counts = [0] * 26 + + for c in s: + counts[ord(c) - ord("a")] += 1 + + sorted_str = "" + for i in range(26): + sorted_str += chr(i + ord("a")) * counts[i] + + return sorted_str + + +# print(solution('hello')) +# print(solution('algorithm')) \ No newline at end of file diff --git a/HHNAM/51to60/55.py b/HHNAM/51to60/55.py new file mode 100644 index 0000000..362287a --- /dev/null +++ b/HHNAM/51to60/55.py @@ -0,0 +1,24 @@ +def solution(arr1, arr2): + merged = [] + i, j = 0, 0 + + while i < len(arr1) and j < len(arr2): + if arr1[i] <= arr2[j]: + merged.append(arr1[i]) + i += 1 + else: + merged.append(arr2[j]) + j += 1 + + while i < len(arr1): + merged.append(arr1[i]) + i += 1 + while j < len(arr2): + merged.append(arr2[j]) + j += 1 + + return merged + + +# print(solution([1, 3, 5], [2, 4, 6])) +# print(solution([1, 2, 3], [4, 5, 6])) \ No newline at end of file diff --git a/HHNAM/51to60/56.py b/HHNAM/51to60/56.py new file mode 100644 index 0000000..f890c50 --- /dev/null +++ b/HHNAM/51to60/56.py @@ -0,0 +1,2 @@ +def solution(strings, n): + return sorted(strings, key=lambda x: (x[n], x)) \ No newline at end of file diff --git a/HHNAM/51to60/57.py b/HHNAM/51to60/57.py new file mode 100644 index 0000000..6ff3808 --- /dev/null +++ b/HHNAM/51to60/57.py @@ -0,0 +1,5 @@ +def solution(n): + digits = list(str(n)) + digits.sort(reverse=True) + answer = int("".join(digits)) + return answer \ No newline at end of file diff --git a/HHNAM/51to60/58.py b/HHNAM/51to60/58.py new file mode 100644 index 0000000..b9b787a --- /dev/null +++ b/HHNAM/51to60/58.py @@ -0,0 +1,8 @@ +def solution(array, commands): + answer = [] + for cmd in commands: + i, j, k = cmd + sliced_arr = array[i - 1 : j] + sorted_arr = sorted(sliced_arr) + answer.append(sorted_arr[k - 1]) + return answer \ No newline at end of file diff --git a/HHNAM/51to60/59.py b/HHNAM/51to60/59.py new file mode 100644 index 0000000..b750057 --- /dev/null +++ b/HHNAM/51to60/59.py @@ -0,0 +1,11 @@ +import functools + +def compare(a, b): + t1 = str(a) + str(b) + t2 = str(b) + str(a) + return (int(t1) > int(t2)) - (int(t1) < int(t2)) + +def solution(numbers): + sorted_nums = sorted(numbers, key=functools.cmp_to_key(compare), reverse=True) + answer = "".join(str(x) for x in sorted_nums) + return "0" if int(answer) == 0 else answer \ No newline at end of file diff --git a/HHNAM/51to60/60.py b/HHNAM/51to60/60.py new file mode 100644 index 0000000..d84e77e --- /dev/null +++ b/HHNAM/51to60/60.py @@ -0,0 +1,11 @@ +def solution(s): + s = s[2:-2].split("}, {") + s = sorted(s, key=len) + answer = [] + for element in s: + numbers = element.split(",") + for number in numbers: + if int(number) not in answer: + answer.append(int(number)) + + return answer \ No newline at end of file diff --git a/MSKIM/31to40/31.py b/MSKIM/31to40/31.py new file mode 100644 index 0000000..d15f9bf --- /dev/null +++ b/MSKIM/31to40/31.py @@ -0,0 +1,12 @@ +from collections import Counter + +n = int(input()) +n_list = list(map(int, input().split())) +m = int(input()) +m_list = list(map(int, input().split())) + +counter = Counter(n_list) + +answer = [counter[i] for i in m_list] + +print(" ".join(map(str, answer))) diff --git a/MSKIM/31to40/38.py b/MSKIM/31to40/38.py new file mode 100644 index 0000000..984a418 --- /dev/null +++ b/MSKIM/31to40/38.py @@ -0,0 +1,30 @@ +#난 dic쓸거임 + +def solution(graph, start): + adj_list = {} + + for u, v in graph: + if u in adj_list: + adj_list[u].append(v) + else: + adj_list[u] = [v] + + + def dfs(node, visited, result): + visited.add(node) + result.append(node) + + if node in adj_list: + for neighbor in adj_list[node]: + if neighbor not in visited: + dfs(neighbor, visited, result) + + visited = set() + result = [] + dfs(start, visited, result) + return result + +graph = [['A', 'B'], ['A', 'C'], ['B', 'D'], ['B', 'E'], ['C', 'F'], ['E', 'F']] +start_node = 'A' + +print(solution(graph, start_node)) diff --git a/MSKIM/31to40/39.py b/MSKIM/31to40/39.py new file mode 100644 index 0000000..d363ac3 --- /dev/null +++ b/MSKIM/31to40/39.py @@ -0,0 +1,35 @@ +from collections import deque + +def solution(graph, start): + adj_list = {} # + for u, v in graph: + if u in adj_list: + adj_list[u].append(v) + else: + adj_list[u] = [v] + + + def bfs(start): + visited = set() + queue = deque([start]) + visited.add(start) + result = [start] + + while queue: + node = queue.popleft() + if node in adj_list: + for neighbor in adj_list[node]: + if neighbor not in visited: + queue.append(neighbor) + visited.add(neighbor) + result.append(neighbor) + + return result + + return bfs(start) + + +graph = [['A', 'B'], ['A', 'C'], ['B', 'D'], ['B', 'E'], ['C', 'F'], ['E', 'F']] +start_node = 'A' + +print(solution(graph, start_node)) diff --git a/MSKIM/31to40/40.py b/MSKIM/31to40/40.py new file mode 100644 index 0000000..fe90eea --- /dev/null +++ b/MSKIM/31to40/40.py @@ -0,0 +1,38 @@ +import heapq + +def solution(graph, start): + distances = {node: float("inf") for node in graph} + distances[start] = 0 + queue = [] + + heapq.heappush(queue, [distances[start], start]) + paths = {start: [start]} + + while queue: + current_distance, current_node = heapq.heappop(queue) + + if distances[current_node] < current_distance: + continue + + for adjacent_node, weight in graph[current_node].items(): + distance = current_distance + weight + + if distance < distances[adjacent_node]: + distances[adjacent_node] = distance + paths[adjacent_node] = paths[current_node] + [adjacent_node] + + heapq.heappush(queue, [distance, adjacent_node]) + + sorted_paths = {node: paths[node] for node in sorted(paths)} + return [distances, sorted_paths] + + +graph = { + 'A': {'B': 1, 'C': 4}, + 'B': {'A': 1, 'C': 2, 'D': 5}, + 'C': {'A': 4, 'B': 2, 'D': 1}, + 'D': {'B': 5, 'C': 1} +} +start_node = 'A' + +print(solution(graph, start_node)) diff --git a/README.md b/README.md index ebf11ce..86e0530 100644 --- a/README.md +++ b/README.md @@ -23,25 +23,25 @@