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 @@ Python : 28    Java : 14    C : 0     C++ : 0     C# : 0 김민승 - 27 - 27 - 73 - -73000 - Python : 27    Java : 0    C : 0     C++ : 0     C# : 0 + 31 + 31 + 69 + -69000 + Python : 31    Java : 0    C : 0     C++ : 0     C# : 0 남현호 - 4 - 4 - 96 - -96000 - Python : 4    Java : 0    C : 0     C++ : 0     C# : 0 + 60 + 60 + 40 + -40000 + Python : 60    Java : 0    C : 0     C++ : 0     C# : 0 류정민 - 10 - 10 - 90 - -90000 - Python : 10    Java : 0    C : 0     C++ : 0     C# : 0 + 12 + 12 + 88 + -88000 + Python : 12    Java : 0    C : 0     C++ : 0     C# : 0 이창석 5 @@ -51,14 +51,14 @@ Python : 5    Java : 0    C : 0     C++ : 0     C# : 0 최수연 - 22 - 24 - 78 - -78000 - Python : 24    Java : 0    C : 0     C++ : 0     C# : 0 + 33 + 35 + 67 + -67000 + Python : 35    Java : 0    C : 0     C++ : 0     C# : 0
-총 Push 횟수 : 120회 +총 Push 횟수 : 145회 # 업로드 방법 ### 1. 파일명 diff --git a/SYCHOI/11to20/19.py b/SYCHOI/11to20/19.py new file mode 100644 index 0000000..92731e8 --- /dev/null +++ b/SYCHOI/11to20/19.py @@ -0,0 +1,25 @@ +def polynomial_hash(str) : + p = 31 + m = 1000000007 + hash_value = 0 + + for char in str : + hash_value = (hash_value * p + ord(char)) % m # why??? + return hash_value + +def solution(string_list, query_list) : + # string_list에 있는 문자열들을 해싱해서 hash_list에 저장 + hash_list = [polynomial_hash(str) for str in string_list] + + result = [] + for query in query_list : + query_hash = polynomial_hash(query) # query_list에 있는 문자열(query)들을 해싱해서 query_hash에 저장 + if query_hash in hash_list : + result.append(True) # 해당 해싱값이 hash_list에 있으면 True 저장 + else : + result.append(False) # 해당 해싱값이 hash_list에 없으면 False 저장 + return result + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution(["apple", "banana", "cherry"], ["banana", "kiwi", "melon", "apple"])) \ No newline at end of file diff --git a/SYCHOI/21to30/21.py b/SYCHOI/21to30/21.py new file mode 100644 index 0000000..6fd2d7c --- /dev/null +++ b/SYCHOI/21to30/21.py @@ -0,0 +1,30 @@ +def solution(want, number, discount) : + dic = {} + + # 정현이가 원하는 제품과 개수를 dictionary에 저장 + for i in range(len(want)) : + dic[want[i]] = number[i] + + # 할인 상품과 원하는 제품 비교 + cnt = 0 # 원하는 제품을 모두 할인받을 수 있는 회원 등록 날짜 수 + for j in range(len(discount) - 9) : # 10일 순회할 수 있을 만큼만 discount 순회 + tenDays = {} + + for k in range(j, j + 10) : # 특정 날짜(k)부터 10일간 discount 물품 순회 + if discount[k] in dic : # 할인 품목이 정현이가 원하는 제품 목록에 있으면 + tenDays[discount[k]] = tenDays.get(discount[k], 0) + 1 # 10일동안 할인받는 물품들의 개수를 tenDays 딕셔너리에 저장 + # tenDays에 이미 있으면 해당 값(value) + 1, 없으면 기본값(default value) + 1 + if tenDays == dic : + cnt += 1 # 10일 연속으로 원하는 제품을 개수만큼 할인받을 수 있다면 cnt++ + break # 책과 다름. 조금 수정함.. + + + return cnt + + + + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution(["banana", "apple", "rice", "pork", "pot"], [3, 2, 2, 2, 1], ["chicken", "apple", "apple", "banana", "rice", "apple", "pork", "banana", "pork", "rice", "pot", "banana", "apple", "banana"])) +print(solution(["apple"], [10], ["banana", "banana", "banana", "banana", "banana", "banana", "banana", "banana", "banana", "banana"])) \ No newline at end of file diff --git a/SYCHOI/21to30/27.py b/SYCHOI/21to30/27.py new file mode 100644 index 0000000..343cb31 --- /dev/null +++ b/SYCHOI/21to30/27.py @@ -0,0 +1,60 @@ +# 포인터 Node 만드는 방법(class Node)와 이진탐색트리 만드는 방법(class BST)는 반드시 익혀두기!! + +class Node : # 포인터로 트리 표현하기 + def __init__(self, key) : # 클래스의 첫 def(__init__)의 첫번째 인수는 무조건 self임. 호출 시 사용x + self.left = None # 왼쪽 자식 노드 + self.right = None # 오른쪽 자식 노드 + self.val = key # 현재 노드의 값 + +class BST : # Binary Search Tree + def __init__(self) : + self.root = None + + # Binary Search Tree(이진탐색트리) 만드는 함수 + def insert(self, key) : # key == 추가하려고 하는 값 + if not self.root : # self.root가 없으면 + self.root = Node(key) # 'Node' 클래스를 통해 self.root 선언 + else : # self.root가 있으면 + curr = self.root # curr에 self.root 값 저장 + while True : + if key < curr.val : # key 값이 BST의 현재 값보다 작으면 + if curr.left : + curr = curr.left # 왼쪽 노드가 있으면 현재 값 = 왼쪽 노드 값 + else : + curr.left = Node(key) # 왼쪽 노드가 없으면 왼쪽 노드에 현재 값 넣은 노드 생성(break) + break + else : # key 값이 BST의 현재 값보다 크면 + if curr.right : + curr = curr.right # 오른쪽 노드가 있으면 현재 값 = 오른쪽 노드 값 + else : + curr.right = Node(key) # 오른쪽 노드가 없으면 오른쪽 노드에 현재 값 넣은 노드 생성(break) + break + + # Binary Search Tree(이진탐색트리) 탐색하는 함수 + def search(self, key) : # key == 찾으려고 하는 값 + curr = self.root # 트리의 루트 값을 기본 값으로 설정 + while curr and curr.val != key : # 현재 값(루트 값)이 key(찾는 값)가 아니면 실행 + if key < curr.val : + curr = curr.left # 찾는 값이 현재 값보다 작으면 왼쪽 노드로 이동 + else : + curr = curr.right # 찾는 값이 현재 값보다 크면 오른쪽 노드로 이동 + return curr # while문을 벗어나면(현재 값 == 찾는 값) 현재 값 리턴 + +def solution(lst, search_lst) : + idx = BST() # idx에 BST 클래스 입력 + for n in lst : + idx.insert(n) # lst에 있는 값들을 순서대로 idx 클래스의 insert 함수로 추가 + + result = [] + for m in search_lst : + if idx.search(m) : + result.append(True) + else : + result.append(False) + + return result + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution([5, 3, 8, 4, 2, 1, 7, 10], [1, 2, 5, 6])) +print(solution([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])) \ No newline at end of file diff --git a/SYCHOI/21to30/28.py b/SYCHOI/21to30/28.py new file mode 100644 index 0000000..87aafdc --- /dev/null +++ b/SYCHOI/21to30/28.py @@ -0,0 +1,14 @@ +def solution(N, A, B) : + result = 1 + while (1) : + A = int((A + 1) / 2) # A = (A + 1) // 2 + B = int((B + 1) / 2) # B = (B + 1) // 2 + if A == B : + break + result += 1 + + return result + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution(8, 4, 7)) \ No newline at end of file diff --git a/SYCHOI/21to30/29.py b/SYCHOI/21to30/29.py new file mode 100644 index 0000000..d1a294a --- /dev/null +++ b/SYCHOI/21to30/29.py @@ -0,0 +1,37 @@ +import math + +def solution(enroll, referral, seller, amount) : + dict = {} + earn = {} + for i in range(len(enroll)) : + dict[enroll[i]] = referral[i] + earn[enroll[i]] = 0 + + for i in range(len(seller)) : + name = seller[i] + money = amount[i] * 100 # 칫솔 개당 100원 + + while name != "-" : + if earn[name] == 0 : + earn[name] = money * 0.9 + else : + earn[name] += money * 0.9 + money = money * 0.1 # referral이 enroll한테 넘겨받은 돈(10%) + if money < 1 : + earn[name] += money # 10%를 계산한 금액이 1원 미만이면 이득을 분배하지 않고 자신이 모두 가짐 + name = dict[name] # referral을 name에 초기화 + + result = [] + for value in earn.values() : + result.append(round(value)) + return result + + + + + + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution(["john", "mary", "edward", "sam", "emily", "jaimie", "tod", "young"], ["-", "-", "mary", "edward", "mary", "mary", "jaimie", "edward"], ["young", "john", "tod", "emily", "mary"], [12, 4, 2, 5, 10])) +print(solution(["john", "mary", "edward", "sam", "emily", "jaimie", "tod", "young"], ["-", "-", "mary", "edward", "mary", "mary", "jaimie", "edward"], ["sam", "emily", "jaimie", "edward"], [2, 3, 5, 4])) \ No newline at end of file diff --git a/SYCHOI/21to30/30.py b/SYCHOI/21to30/30.py new file mode 100644 index 0000000..9e155a8 --- /dev/null +++ b/SYCHOI/21to30/30.py @@ -0,0 +1,55 @@ +from collections import deque + +def isValid(ny, nx, n, m, maps) : + return 0 <= ny < n and 0 <= nx < m and maps[ny][nx] != "X" + # 0 <= ny < n : 방문할 y좌표가 지도 내에 있고 / 0 <= nx < m : 방문할 x좌표가 지도 내에 있고 + # 방문할 좌표가 벽이 아니면 return + +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)) # time + 1 상태 q에 append + +def solution(maps) : + n, m = len(maps), len(maps[0]) # n : maps의 행 개수, m : maps의 열 개수 + visited = [[[False for _ in range(2)] for _ in range(m)] for _ in range(n)] # [False, False]를 m개의 열 개수만큼, n개의 행 개수만큼 생성 + # False for _ in range(2) : [False, False] 생성 + + # dy, dx의 인덱스에 따라 상/하/좌/우 구별 가능 : dx[0] & dy[0] = 위로 이동 + dy = [-1, 1, 0, 0]; dx = [0, 0, -1, 1] + endY, endX = -1, -1 # 도착점의 x, y 좌표 넣는 변수. -1로 초기화한다 + q = deque() # q라는 변수에 덱 기능 선언 + + for i in range(n) : + for j in range(m) : + if maps[i][j] == "S" : + q.append((i, j, 0, 0)) # 덱 q에 시작점 좌표 입력 (q의 오른쪽 끝에 삽입) + visited[i][j][0] = True # (i, j) 좌표 방문 표시 + if maps[i][j] == "E" : + endY, endX = i, j # (i, j) 출구 좌표 입력 + + while q : + y, x, k, time = q.popleft() # (q의 왼쪽 끝 원소 pop) + # y좌표 , x좌표, 레버 동작 여부, 시작 지점부터 해당 좌표까지 가는 데 걸린 시간 + + if y== endY and x == endX and k == 1 : # 왜 k == 1이어야 할까..? + return time + + for i in range(4) : # 현재 좌표(y, x)에서 상하좌우 1칸씩 이동 + ny, nx = y + dy[i], x + dx[i] # 이동한 좌표 ny, nx에 저장 + + if not isValid(ny, nx, n, m, maps) : + continue # 이동 불가한 위치라면 continue + + if maps[ny][nx] == "L" : + append_to_Queue(ny, nx, 1, time, visited, q) # 이동한 곳이 레버라면 k = 1 적용 + else : + append_to_Queue(ny, nx, k, time, visited, q) # 이동한 곳이 레버가 아니라면 k = 0(그대로) + + return -1 + + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution(["SOOOL", "XXXXO", "OOOOO", "OXXXX", "OOOOE"])) +print(solution(["LOOXS", "OOOOX", "OOOOO", "OOOOO", "EOOOO"])) \ No newline at end of file diff --git a/SYCHOI/31to40/32.py b/SYCHOI/31to40/32.py new file mode 100644 index 0000000..0d65292 --- /dev/null +++ b/SYCHOI/31to40/32.py @@ -0,0 +1,88 @@ +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) : + # 노드의 개수만큼 1부터 노드길이 + 1까지의 리스트 생성 + nodes = [i for i in range(1, len(nodeinfo) + 1)] + + # y좌표 내림차순 정렬, y좌표가 같을 때 x좌표 오름차순 정렬 (y축은 크고 x축은 작은 노드의 인덱스값 정렬) + # nodes의 원소는 1부터, nodesinfo의 원소는 0부터 시작하므로 nodeinfo의 1차원 리스트에 대해서 x - 1 적용 + nodes.sort(key = lambda x : (nodeinfo[x - 1][1], -nodeinfo[x - 1][0]), reverse=True) + root = None # 루트 노드 초기화(None으로) + + # root를 기준으로 순회해서 트리에 노드 추가 + for i in range(len(nodes)) : + if root is None : + root = Node(nodeinfo[nodes[0] - 1], nodes[0]) # 'root' 노드의 info = nodeinfo[nodes[0] - 1], num = nodes[0] + else : + parent = root + node = Node(nodeinfo[nodes[i] - 1], nodes[i]) # 자식 노드들의 info = nodeinfo[nodes[i] - 1], num = nodes[i] + + while True : + # info[0] : 해당 노드(node, parent)의 x좌표 + if node.info[0] < parent.info[0] : # parent의 x좌표가 node보다 크면 + if parent.has_left() : + parent = parent.left # parent의 왼쪽 노드에 값이 있으면 현재 parent를 parent의 왼쪽 노드로 + continue + parent.left = node # parent의 왼쪽 노드에 값이 없으면 node 삽입 + break + else : # node의 x좌표가 parent보다 크면 + if parent.has_right() : + parent = parent.right # parent의 오른쪽 노드에 값이 있으면 현재 parent를 parent의 오른쪽 노드로 + continue + parent.right = node # parent의 오른쪽 노드에 값이 없으면 node 삽입 + break + return root + + +def pre_order(root, answer) : # 생성한 이진트리의 root, 전위순회를 담을 answer 리스트(answer[0]) + stack = [root] # stack에 root 노드 삽입 + while stack : + node = stack.pop() # stack의 최상단 노드 방문 + if node is None : + continue # 부모 노드의 왼쪽or오른쪽 노드가 없을 경우 + answer[0].append(node.num) # 방문한 노드의 값 answer[0]에 append + stack.append(node.right) + stack.append(node.left) # stack은 LIFO이기 때문에 먼저 방문할 왼쪽 노드를 나중에 삽입 + + +def post_order(root, answer) : # 생성한 이진트리의 root, 후위순회를 담을 answer 리스트(answer[1]) + stack = [(root, False)] # stack에 root 노드 & 방문 여부 삽입 + while stack : + node, visited = stack.pop() # stack의 최상단 노드 방문 + if node is None : + continue # 부모 노드의 왼쪽or오른쪽 노드가 없을 경우 + 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) # 입력받은 노드의 좌표(nodeinfo)를 통해 이진 트리 생성 + pre_order(root, answer) + post_order(root, answer) + + return answer + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +print(solution([[5, 3], [11, 5], [13, 3], [3, 5], [6, 1], [1, 3], [8, 6], [7, 2], [2, 2]])) \ No newline at end of file diff --git a/SYCHOI/31to40/33.py b/SYCHOI/31to40/33.py new file mode 100644 index 0000000..f563347 --- /dev/null +++ b/SYCHOI/31to40/33.py @@ -0,0 +1,35 @@ +# 리스트 형식의 result를 전역변수로 생성했었음. 하지만 파이썬에서는 전역변수를 사용할 때 매 함수마다 'global 전역변수명' 형식으로 호출해줘야 하기 때문에 번거로움. 그냥 함수의 매개변수로 호출 + +def find(result, x) : # x가 속한 집합의 대표 원소(Root) 찾기 + if result[x] == x : + return result[x] # 인덱스 값 == 노드 값 : 부모 노드(Root) + + parent = find(result, result[x]) # 인덱스 값 != 노드 값 : 자식 노드 => 부모노드 찾기(재귀함수) + return parent + +def union(result, x, y) : # x와 y가 속한 두 집합 합치기 + root1 = find(result, x) + root2 = find(result, y) # 각 노드(x, y)가 속한 집합의 루트 노드 찾기 + + result[root2] = root1 # y가 속한 집합의 루트노드(root2)를 x가 속한 집합의 루트노드(root1)와 합치기 + + +def solution(k, operations) : + # 노드의 값 : 인덱스 , 부모노드 : 리스트 값 + result = list(range(k)) # 처음에는 각 노드가 자기 자신을 부모로 가지도록 초기화 + n = k + + for lst in operations : + if lst[0] == 'u' : + union(result, lst[1], lst[2]) + # print(lst[0], lst[1], lst[2]) + # elif lst[0] == 'f' : + # root = find(lst[1]) + # print(lst[0], lst[1]) + + n = len(set(find(result, i) for i in range(k))) + return n + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +# 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/SYCHOI/31to40/34.py b/SYCHOI/31to40/34.py new file mode 100644 index 0000000..93c9816 --- /dev/null +++ b/SYCHOI/31to40/34.py @@ -0,0 +1,26 @@ +def solution(nums) : # nums : 폰켓몬의 종류 번호가 담긴 1차원 배열 + halfN = len(nums) // 2 # int(len(nums) / 2) + idx = [0 for i in range(max(nums) + 1)] + + cnt = 0 + for n in nums : + if idx[n] == 0 : + cnt += 1 + idx[n] = 1 + + if halfN == cnt : + return halfN + + # 책의 예시(더 쉬운 방법) + # num_set = set(nums) # 폰켓몬 종류의 번호를 중복이 없는 집합으로 생성 + # n = len(nums) + # k = n // 2 # k는 최대 뽑을 수 있는 폰켓몬의 수 + # return min(k, len(num_set)) # 폰켓몬 종류 수(num_set)와 뽑을 수 있는 폰켓몬의 수(k) 중에 작은 값을 리턴 + + return cnt + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +# print(solution([3, 1, 2, 3])) +# print(solution([3, 3, 3, 2, 2, 4])) +# print(solution([3, 3, 3, 2, 2, 2])) \ No newline at end of file diff --git a/SYCHOI/31to40/35.py b/SYCHOI/31to40/35.py new file mode 100644 index 0000000..20ebb4e --- /dev/null +++ b/SYCHOI/31to40/35.py @@ -0,0 +1,31 @@ +def solution(n, words) : + result = [] + listUp = [] + idx = 1; round = 1; first = 1 + + for word in words : + if word in listUp : + return [idx, round] # 이미 나온 단어(listUp)가 나오면 리턴 + + if first == 0 and word[0] != last : + return [idx, round] # (첫단어 제외) 이전 단어의 마지막 알파벳과 현재 단어의 첫 알파벳이 다르면 리턴 + + if idx == n : + idx = 1 + round += 1 + else : + idx += 1 + + first = 0 + last = word[-1] + listUp.append(word) + + # words 리스트를 무사히 순회하면 [0, 0] 리턴 + return [0, 0] + + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +# print(solution(3, ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"])) +# print(solution(5, ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"])) +# print(solution(2, ["hello", "one", "even", "never", "now", "world", "draw"])) \ No newline at end of file diff --git a/SYCHOI/31to40/36.py b/SYCHOI/31to40/36.py new file mode 100644 index 0000000..57f8ed3 --- /dev/null +++ b/SYCHOI/31to40/36.py @@ -0,0 +1,15 @@ +def solution(phone_book) : + # 접두어가 겹치는지 쉽게 확인하는 방법 : 정렬 + phone_book.sort() + + for i in range(len(phone_book)-1) : # 두 개를 비교할 것이기 때문에 phone_book -1까지 비교 + if phone_book[i + 1].startswith(phone_book[i]) : # startswith() : 앞의 변수가 매개변수로 시작하는지 분별 + return False # 어떤 번호가 다른 번호의 접두어이면 False + + return True # 그렇지 않으면 True + + +#TEST 코드입니다. 주석을 풀어서 확인해보세요 +# print(solution(["119", "97674223", "1195524421"])) +# print(solution(["123", "456", "789"])) +# print(solution(["12", "123", "1235", "567", "88"])) \ No newline at end of file diff --git a/total_push_cnt.txt b/total_push_cnt.txt index 52bd8e4..13c09a0 100644 --- a/total_push_cnt.txt +++ b/total_push_cnt.txt @@ -1 +1 @@ -120 +145