diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/algorithm-study.iml b/.idea/algorithm-study.iml new file mode 100644 index 0000000..f392c3c --- /dev/null +++ b/.idea/algorithm-study.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..0dd4b35 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/libraries/KotlinJavaRuntime.xml b/.idea/libraries/KotlinJavaRuntime.xml new file mode 100644 index 0000000..a209aee --- /dev/null +++ b/.idea/libraries/KotlinJavaRuntime.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..dda7141 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..7499006 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/changyeop/BST.py b/changyeop/BST.py new file mode 100644 index 0000000..89d3aba --- /dev/null +++ b/changyeop/BST.py @@ -0,0 +1,68 @@ +from re import T + + +class Node: + def __init__(self, val) -> None: + self.val = val + self.left = None + self.right = None + pass + +class BST: + def __init__(self, root: Node) -> None: + self.root = root + + def insert(self, val): + self.root = self._insert_value(self.root, val=val) + return self.root is not None + + def _insert_value(self, node, val): + if node is None: + node = Node(val) + else: + if val <= node.val: + node.left = self._insert_value(node.left, val) + else: + node.right = self._insert_value(node.right,val) + return node + + def search(self, val): + return self._search_value(self.root, val) + + def _search_value(self, root, val): + if root is None or root.val == val: + return root is not None + elif val < root.val: + return self._search_value(root.left, val) + else: + return self._search_value(root.right, val) + + def delete(self, val): + self.root, is_deleted = self._delete_value(self.root, val) + return is_deleted + + def _delete_value(self, node, val): + if node is None: + return node, False + + is_deleted = False + if node.val == val: + is_deleted = True + if node.left and node.right: + parent, child = node, node.right + while child.left is not None: + parent, child = child, child.left + child.left = node.left + if parent != node: + parent.left = child.right + child.right = node.right + node = child + elif node.left or node.right: + node = node.left or node.right + else: + node = None + elif val < node.val: + node.left, is_deleted = self._delete_value(node.left, val) + else: + node.right, is_deleted = self._delete_value(node.right, val) + return node, is_deleted \ No newline at end of file diff --git a/changyeop/BubbleSort.py b/changyeop/BubbleSort.py new file mode 100644 index 0000000..b8c103c --- /dev/null +++ b/changyeop/BubbleSort.py @@ -0,0 +1,8 @@ +from typing import List + + +def bubble(arr: List[int]): + for i in range(len(arr) - 1, 0, -1): + for j in range(i): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] \ No newline at end of file diff --git a/changyeop/CircularQueue.py b/changyeop/CircularQueue.py new file mode 100644 index 0000000..4a17f29 --- /dev/null +++ b/changyeop/CircularQueue.py @@ -0,0 +1,34 @@ +class MyCircularQueue: + def __init__(self, k: int) -> None: + self.q = [None] * k + self.maxLen = k + self.p1 = 0 # front + self.p2 = 0 # rear + + def enqueue(self, value: int): + if self.q[self.p2] is None: + self.q[self.p2] = value + self.p2 = (self.p2 + 1) % self.maxLen + return True + else: + return False + + def dequeue(self): + if self.q[self.p1] is None: + return False + else: + self.q[self.p1] = None + self.p1 = (self.p1 + 1) % self.maxLen + return True + + def Front(self): + return -1 if self.q[self.p1] is None else self.q[self.p1] + + def Rear(self): + return -1 if self.q[self.p2 - 1] is None else self.q[self.p2 - 1] + + def isEmpty(self): + return self.p1 == self.p2 and self.q[self.p1] is None + + def isFull(self): + return self.p1 == self.p2 and self.q[self.p1] is not None \ No newline at end of file diff --git a/changyeop/Combination.py b/changyeop/Combination.py new file mode 100644 index 0000000..a02fc4e --- /dev/null +++ b/changyeop/Combination.py @@ -0,0 +1,15 @@ +def combine(n: int, k: int): + result = [] + + def dfs(items, start: int, k: int): + if k == 0: + result.append(items[:]) + return + + for i in range(start, n+1): + items.append(i) + dfs(items, i+1, k-1) + items.pop() + dfs([], 1, k) + + return result \ No newline at end of file diff --git a/changyeop/CombinationSum.py b/changyeop/CombinationSum.py new file mode 100644 index 0000000..55b0845 --- /dev/null +++ b/changyeop/CombinationSum.py @@ -0,0 +1,18 @@ +from typing import List + + +def combinationSum(candidates: List[int], target: int): + result = [] + + def dfs(cur_sum, index, path): + if cur_sum > target: + return + if cur_sum == target: + result.append(path[:]) + return + + for i in range(index, len(candidates)): + dfs(cur_sum+candidates[i], i, path+[candidates[i]]) + + dfs(target, 0, []) + return result \ No newline at end of file diff --git a/changyeop/HeapSort.py b/changyeop/HeapSort.py new file mode 100644 index 0000000..5d4a348 --- /dev/null +++ b/changyeop/HeapSort.py @@ -0,0 +1,21 @@ +def heapify(li, index, n): + l = index * 2 + 1 + r = index * 2 + 2 + s_idx = index + if l <= n and li[s_idx] > li[l]: + s_idx = l + if r <= n and li[s_idx] > li[r]: + s_idx = r + if s_idx != index: + li[index], li[s_idx] = li[s_idx], li[index] + return heapify(li, s_idx, n) +def heap_sort(arr): + n = len(arr) + + for i in range(n // 2 - 1, -1, -1): + heapify(arr, i, n) + + for i in range(n-1, 0, -1): + arr[0], arr[i] = arr[i], arr[0] + heapify(arr, 0, i) + return arr \ No newline at end of file diff --git a/changyeop/InsertionSort.py b/changyeop/InsertionSort.py new file mode 100644 index 0000000..d5ebb62 --- /dev/null +++ b/changyeop/InsertionSort.py @@ -0,0 +1,5 @@ +def insertion(arr): + for end in range(1, len(arr)): + for i in range(end, 0, -1): + if arr[i-1] > arr[i]: + arr[i-1], arr[i] = arr[i], arr[i-1] \ No newline at end of file diff --git a/changyeop/Leet_3_M.py b/changyeop/Leet_3_M.py new file mode 100644 index 0000000..e6ff990 --- /dev/null +++ b/changyeop/Leet_3_M.py @@ -0,0 +1,17 @@ +def lengthOfLongestSubstring(s: str) -> int: + # add char -> if appear contained char -> make new string : 'dvdf' 경우 틀림 + answer = 0 + output = '' + for c in s: + if c in output: + # make new string + start = output.index(c) + output = output[start+1:] + output += c + else: + output += c + answer = max(answer, len(output)) + + return answer + +print(lengthOfLongestSubstring(s='dvdf')) \ No newline at end of file diff --git a/changyeop/LongestSubstring.py b/changyeop/LongestSubstring.py new file mode 100644 index 0000000..f6f7f27 --- /dev/null +++ b/changyeop/LongestSubstring.py @@ -0,0 +1,10 @@ +def lengthOfSubstring(s: str): + used = {} + maxLen, start = 0, 0 + for index, char in enumerate(s): + if char in used and start <= used[char]: + start = used[char] + 1 + else: + maxLen = max(maxLen, index - start + 1) + used[char] = index + return maxLen \ No newline at end of file diff --git a/changyeop/MergeSort.py b/changyeop/MergeSort.py new file mode 100644 index 0000000..05e728f --- /dev/null +++ b/changyeop/MergeSort.py @@ -0,0 +1,22 @@ +def merge_sort(arr): + + if len(arr) < 2: + return arr + + mid = len(arr) // 2 + low_arr = merge_sort(arr[:mid]) + high_arr = merge_sort(arr[mid:]) + + merged_arr = [] + + l = h = 0 + while l < len(low_arr) and h < len(high_arr): + if low_arr[l] < high_arr[h]: + merged_arr.append(low_arr[l]) + l += 1 + else: + merged_arr.append(high_arr[h]) + h += 1 + merged_arr += low_arr[l:] + merged_arr += low_arr[:h] + return merged_arr \ No newline at end of file diff --git a/changyeop/MostCommonWord.py b/changyeop/MostCommonWord.py new file mode 100644 index 0000000..4859d1c --- /dev/null +++ b/changyeop/MostCommonWord.py @@ -0,0 +1,9 @@ +from collections import Counter +import re +from typing import List + + +def solution(paragraph: str, banned: List[str]): + words = [w for w in re.sub(r'[^\w]', ' ', paragraph).lower().split() if w not in banned] + counts = Counter(words) + return counts.most_common(1)[0][0] diff --git a/changyeop/Permutation.py b/changyeop/Permutation.py new file mode 100644 index 0000000..d278ddd --- /dev/null +++ b/changyeop/Permutation.py @@ -0,0 +1,21 @@ +from typing import List + + +def permute(nums: List[int]): + result = [] + perm = [] + + def dfs(items): + if len(items) == 0: + result.append(perm[:]) + return + for i in items: + next_items = items[:] + next_items.remove(i) + perm.append(i) + dfs(next_items) + perm.pop() + + dfs(nums) + + return result diff --git a/changyeop/QueueByStack.py b/changyeop/QueueByStack.py new file mode 100644 index 0000000..c92580b --- /dev/null +++ b/changyeop/QueueByStack.py @@ -0,0 +1,20 @@ +class MyQueue: + def __init__(self) -> None: + self.input = [] + self.output = [] + + def push(self, x): + self.input.append(x) + + def peek(self): + if not self.output: + while self.input: + self.output.append(self.input.pop()) + return self.output[-1] + + def pop(self): + self.peek() + return self.output.pop() + + def empty(self): + return self.input == [] and self.output == [] \ No newline at end of file diff --git a/changyeop/QuickSort.py b/changyeop/QuickSort.py new file mode 100644 index 0000000..96f73b6 --- /dev/null +++ b/changyeop/QuickSort.py @@ -0,0 +1,14 @@ +def quick_sort(arr): + if len(arr) <= 1: + return arr + + pivot = arr[len(arr) // 2] + min_arr, equal_arr, max_arr = [], [], [] + for num in arr: + if num < pivot: + min_arr.append(num) + elif num > pivot: + max_arr.append(num) + else: + equal_arr.append(num) + return quick_sort(min_arr) + equal_arr + quick_sort(max_arr) \ No newline at end of file diff --git a/changyeop/RemoveDuplicateLetters.py b/changyeop/RemoveDuplicateLetters.py new file mode 100644 index 0000000..38bc4fd --- /dev/null +++ b/changyeop/RemoveDuplicateLetters.py @@ -0,0 +1,24 @@ +# by recur +from collections import Counter + + +def removeDuplicateLetters(s: str): + for char in sorted(set(s)): + suffix = s[s.index(char):] + if set(s) == set(suffix): + return char + removeDuplicateLetters(suffix.replace(char, '')) + return '' + +def byStack(s: str): + counter, seen, stack = Counter(s), set(), [] + for char in s: + counter[char] -= 1 + if char in seen: + #이미 처리된 문자는 스킵 + continue + while stack and char < stack[-1] and counter[stack[-1]] > 0: + seen.remove(stack.pop()) + stack.append(char) + seen.add(char) + + return ''.join(stack) \ No newline at end of file diff --git a/changyeop/ReverseList.py b/changyeop/ReverseList.py new file mode 100644 index 0000000..7e6e658 --- /dev/null +++ b/changyeop/ReverseList.py @@ -0,0 +1,29 @@ +class ListNode: + def __init__(self, val = 0, next = None) -> None: + self.val = val + self.next = next +class Solution: + def solution(head: ListNode): + + + #반복문 + node, prev = head, None + + while node: + next, node.next = node.next, prev + prev, node = node, next + + return prev + + + # 재귀풀이 + def reverse(node: ListNode, prev: ListNode = None): + if not node: + return prev + next, node.next = node.next, prev + + return reverse(next, node) + + return reverse(head) + + \ No newline at end of file diff --git a/changyeop/SelectionSort.py b/changyeop/SelectionSort.py new file mode 100644 index 0000000..46056cf --- /dev/null +++ b/changyeop/SelectionSort.py @@ -0,0 +1,7 @@ +def selection(arr): + for i in range(len(arr) -1): + min_idx = i + for j in range(i+1, len(arr)): + if arr[j] < arr[min_idx]: + min_idx = j + arr[i], arr[min_idx] = arr[min_idx], arr[i] \ No newline at end of file diff --git a/changyeop/StackByQueue.py b/changyeop/StackByQueue.py new file mode 100644 index 0000000..eba684c --- /dev/null +++ b/changyeop/StackByQueue.py @@ -0,0 +1,20 @@ +import collections + + +class StackByQueue: + def __init__(self) -> None: + self.q = collections.deque() + + def push(self, x): + self.q.append(x) + for _ in range(len(self.q)-1): + self.q.append(self.q.popleft()) + + def pop(self): + return self.q.popleft() + + def top(self): + return self.q[0] + + def empty(self): + return len(self.q) == 0 \ No newline at end of file diff --git a/changyeop/TwoSum.py b/changyeop/TwoSum.py new file mode 100644 index 0000000..9cd59e7 --- /dev/null +++ b/changyeop/TwoSum.py @@ -0,0 +1,23 @@ +from typing import List + + +def solution(nums: List[str], target: int): + nums_map = {} + for i, num in enumerate(nums): + nums_map[num] = i + + for i, num in enumerate(nums): + if target - num in nums_map and i != nums_map[target - num]: + return nums.index(num), nums_map[target - num] + + # 투 포인터 + nums.sort() # 인덱스를 찾는 문제라면 정렬하면 안된다. + left, right = 0, len(nums) - 1 + while not left == right: + if nums[left] + nums[right] < target: + left += 1 + elif nums[left] + nums[right] > target: + right -= 1 + else: + return left, right + \ No newline at end of file diff --git a/changyeop/ValidPalindrome.py b/changyeop/ValidPalindrome.py new file mode 100644 index 0000000..6da4f7d --- /dev/null +++ b/changyeop/ValidPalindrome.py @@ -0,0 +1,34 @@ +from collections import deque +from curses.ascii import isalnum +import re + + +def useList(s: str): + strs = [] + for char in s: + if char.isalnum(): + strs.append(char.lower()) + while len(strs) > 1: + if strs.pop(0) != strs.pop(): # pop(0)의 시간복잡도는 O(n) + return False + + return True + +# 데크 자료형을 사용 +def useDeque(s: str): + strs = deque() + for char in s: + if char.isalnum(): + strs.append(char.lower()) + + while len(strs) > 1: + if strs.popleft() != strs.pop(): # popleft 의 시간복잡도는 O(1) + return False + + return True + +# 슬라이싱을 활용한 경우 +def useSlicing(s: str): + s = s.lower() + s = re.sub('[^a-z0-9]', '', s) # 소문자와 숫자가 아닌 문자들을 ''로 치환한다 + return s == s[::-1] \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_1092_G5.java" "b/changyeop/\353\260\261\354\244\200_1092_G5.java" new file mode 100644 index 0000000..646a60b --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_1092_G5.java" @@ -0,0 +1,49 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +class Main1092 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + int[] cranes = new int[n]; + st = new StringTokenizer(br.readLine()); + for(int i = 0; i < n; i++){ + cranes[i] = Integer.parseInt(st.nextToken()); + } + Arrays.sort(cranes); + st = new StringTokenizer(br.readLine()); + int m = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + ArrayList pq = new ArrayList<>(); + for(int i = 0; i < m; i++){ + int cur = Integer.parseInt(st.nextToken()); + pq.add(cur); + } + pq.sort(Collections.reverseOrder()); + if (pq.get(0) > cranes[n-1]) { + System.out.println(-1); + System.exit(0); + } + int answer = 0; + while(pq.size() > 0){ + answer++; + int curCrane = n-1, curBox = 0; + while(curCrane >= 0){ + if(curBox == pq.size()) break; + // can load + if(pq.get(curBox) <= cranes[curCrane]){ + pq.remove(curBox); + curCrane--; + } else { + curBox++; + } + } + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_11000_G5.java" "b/changyeop/\353\260\261\354\244\200_11000_G5.java" new file mode 100644 index 0000000..514f9c9 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_11000_G5.java" @@ -0,0 +1,43 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +class Main11000 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int[][] times = new int[n][2]; + for(int i = 0; i < n; i++){ + st = new StringTokenizer(br.readLine()); + times[i][0] = Integer.parseInt(st.nextToken()); + times[i][1] = Integer.parseInt(st.nextToken()); + } + Arrays.sort(times, (o1, o2) -> { + if (o1[0] != o2[0]) { + return o1[0] - o2[0]; + } else { + return o1[1] - o2[1]; + } + }); + // 위와 같이 정렬한다고해서 먼저 시작한 강의가 먼저 끝나리라는 보장이 없다 + // 예를들면, [2,8] [3,5] 와 같은 경우 + PriorityQueue ends = new PriorityQueue<>(); + ends.add(times[0][1]); + + for(int i = 1; i < n; i++){ + if(times[i][0] >= ends.peek()) { + ends.poll(); + } + ends.offer(times[i][1]); + } + System.out.println(ends.size()); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_12933_S3.java" "b/changyeop/\353\260\261\354\244\200_12933_S3.java" new file mode 100644 index 0000000..5c0d8df --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_12933_S3.java" @@ -0,0 +1,96 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +/** + * List를 만들어서 새롭게 오리가 추가되는 경우 추가 + * q,u,a,c,k 에 대해 1,2,3,4,5로 저장하고 값을 보고 적절한 원소를 업데이트 + */ + +class Main12933{ + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String input = br.readLine(); + + if(input.charAt(0) != 'q' || input.length() % 5 != 0){ + System.out.println(-1); + return; + } + ArrayList ducks = new ArrayList<>(); + ducks.add(1); + + for(int i = 1; i < input.length(); i++){ + char cur = input.charAt(i); + boolean isFind = false; + if(cur == 'q'){ + for(int j = 0; j < ducks.size(); j++){ + if(ducks.get(j) == 5){ + isFind = true; + ducks.set(j, 1); + break; + } + } + if(!isFind) ducks.add(1); + } else if (cur == 'u') { + for(int j = 0; j < ducks.size(); j++){ + if(ducks.get(j) == 1){ + isFind = true; + ducks.set(j, 2); + break; + } + } + if(!isFind) { + System.out.println(-1); + return; + } + } else if (cur == 'a') { + for(int j = 0; j < ducks.size(); j++){ + if(ducks.get(j) == 2){ + isFind = true; + ducks.set(j, 3); + break; + } + } + if(!isFind) { + System.out.println(-1); + return; + } + } else if (cur == 'c') { + for(int j = 0; j < ducks.size(); j++){ + if(ducks.get(j) == 3){ + isFind = true; + ducks.set(j, 4); + break; + } + } + if(!isFind) { + System.out.println(-1); + return; + } + } else { + for(int j = 0; j < ducks.size(); j++){ + if(ducks.get(j) == 4){ + isFind = true; + ducks.set(j, 5); + break; + } + } + if(!isFind) { + System.out.println(-1); + return; + } + } + } + for(int i : ducks){ + if(i != 5){ + System.out.println(-1); + return; + } + } + System.out.println(ducks.size()); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_16926_S1.java" "b/changyeop/\353\260\261\354\244\200_16926_S1.java" new file mode 100644 index 0000000..e87c11d --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_16926_S1.java" @@ -0,0 +1,61 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +class Main16926{ + + static int[][] arr; + static int n; + static int m; + static int r; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + r = Integer.parseInt(st.nextToken()); + arr = new int[n][m]; + for(int i = 0; i < n; i++){ + st = new StringTokenizer(br.readLine()); + for(int j = 0; j < m; j++){ + arr[i][j] = Integer.parseInt(st.nextToken()); + } + } + //rotate + int rect = Math.min(n, m) / 2; + for(int i = 0; i < r; i++){ + for(int j = 0; j < rect; j++){ + int temp = arr[j][j]; + //top + for(int k = j; k < m - j - 1; k++){ + arr[j][k] = arr[j][k+1]; + } + //right + for(int k = j; k < n - j - 1; k++){ + arr[k][m-j-1] = arr[k+1][m-j-1]; + } + //bottom + for(int k = m - j - 1; k > j; k--){ + arr[n-j-1][k] = arr[n-j-1][k-1]; + } + //left + for(int k = n - j - 1; k > j; k--){ + arr[k][j] = arr[k-1][j]; + } + arr[j+1][j] = temp; + } + } + StringBuilder sb = new StringBuilder(); + for(int[] a: arr){ + for(int b: a){ + sb.append(b).append(" "); + } + sb.append("\n"); + } + System.out.println(sb); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_1715_G4.java" "b/changyeop/\353\260\261\354\244\200_1715_G4.java" new file mode 100644 index 0000000..918caa9 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_1715_G4.java" @@ -0,0 +1,27 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; + +class Main1715 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + PriorityQueue pq = new PriorityQueue<>(); + for(int i = 0; i < n; i++){ + pq.add(Integer.parseInt(br.readLine())); + } + int answer = 0; + // 현재 묶음 중에서 가장 작은 값 두가지를 먼저 더한다 + while(pq.size() > 1){ + int first = pq.poll(); + int second = pq.poll(); + int sum = first + second; + pq.add(sum); + answer += sum; + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_21921_S3.py" "b/changyeop/\353\260\261\354\244\200_21921_S3.py" new file mode 100644 index 0000000..22d98c3 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_21921_S3.py" @@ -0,0 +1,25 @@ +import sys +n, x = map(int, sys.stdin.readline().split(' ')) +# print(n,x) +arr = list(map(int, sys.stdin.readline().split(' '))) +# print(arr) +end = x +res = 0 +for i in range(end): + res += arr[i] +maxRes = res +cnt = 1 +for i in range(end, n, 1): + start = i - x + res = res + arr[i] - arr[start] + if res > maxRes: + maxRes = res + cnt = 1 + elif res == maxRes: + cnt += 1 + +if maxRes == 0: + print('SAD') +else: + print(maxRes) + print(cnt) \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_2212_G5.java" "b/changyeop/\353\260\261\354\244\200_2212_G5.java" new file mode 100644 index 0000000..db9caf0 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_2212_G5.java" @@ -0,0 +1,33 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +class Main2212 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + int k = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + int[] sensors = new int[n]; + for(int i = 0; i < n; i++){ + sensors[i] = Integer.parseInt(st.nextToken()); + } + Arrays.sort(sensors); + int[] diff = new int[n-1]; + for(int i = 0; i < n-1; i++){ + diff[i] = sensors[i+1] - sensors[i]; + } + Arrays.sort(diff); + int answer = 0; + for(int i = 0; i < n-k; i++){ + answer += diff[i]; + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_2252_G3.java" "b/changyeop/\353\260\261\354\244\200_2252_G3.java" new file mode 100644 index 0000000..06a57dc --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_2252_G3.java" @@ -0,0 +1,56 @@ +package changyeop; + +import java.io.*; +import java.util.*; + +/** + * 위상정렬로 푼다 + */ +class Main2252{ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + + // 노드끼리의 순서를 정의하기 위해 2차원 리스트 활용 + ArrayList> graph = new ArrayList<>(); + for(int i = 0; i <= n+1; i++){ + graph.add(new ArrayList<>()); + } + + // 각 노드별로 몇 개의 노드가 선행되어야 하는지 나타내는 배열 + int[] inDegree = new int[n+1]; + + for(int i = 0; i < m; i++){ + st = new StringTokenizer(br.readLine()); + int start = Integer.parseInt(st.nextToken()); + int end = Integer.parseInt(st.nextToken()); + graph.get(start).add(end); // 시작 노드에 연결된 노드 삽입 + inDegree[end]++; // 끝 지점 노드의 인접 노드 개수 1 추가 + } + + Queue q = new LinkedList<>(); // 위상정렬에 활용할 큐 + for(int i = 1; i < inDegree.length; i++){ + if (inDegree[i] == 0) q.add(i); // 인접한 노드가 없는 경우 먼저 큐에 삽입 + } + ArrayList result = new ArrayList<>(); + + while(!q.isEmpty()){ + int cur = q.poll(); + result.add(cur); + // 인접한 노드의 indegree 1 감소 + for(int i = 0; i < graph.get(cur).size(); i++){ + inDegree[graph.get(cur).get(i)]--; + if (inDegree[graph.get(cur).get(i)] < 1){ + q.add(graph.get(cur).get(i)); + } + } + } + + for(int i : result){ + System.out.print(i + " "); + } + System.out.println(""); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_2615_S1.java" "b/changyeop/\353\260\261\354\244\200_2615_S1.java" new file mode 100644 index 0000000..18f6963 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_2615_S1.java" @@ -0,0 +1,62 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +class Solution { + + static int[][] board = new int[19][19]; + + static int[] moveX = {1, 0, 1, 1}; // right, down, up-right, down-right + static int[] moveY = {0, 1, -1, 1}; + + static void bfs(int x, int y) { + + int stone = board[y][x]; + + for(int i = 0; i < 4; i++){ + int nx = x + moveX[i]; + int ny = y + moveY[i]; + int cnt = 1; + while(0<=nx && nx<19 && 0<=ny && ny<19 && board[ny][nx] == stone){ + cnt++; + if(cnt==5){ + int px = x - moveX[i]; + int py = y - moveY[i]; + if (0 <= px && px < 19 && 0 <= py && py < 19 && board[py][px] == stone) break; + px = nx + moveX[i]; + py = ny + moveY[i]; + if (0 <= px && px < 19 && 0 <= py && py < 19 && board[py][px] == stone) break; + System.out.println(stone); + y++; + x++; + System.out.println(y + " " + x); + System.exit(0); + } + nx += moveX[i]; + ny += moveY[i]; + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + for (int i = 0; i < 19; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < 19; j++) { + board[i][j] = Integer.parseInt(st.nextToken()); + } + } + for (int i = 0; i < 19; i++) { + for (int j = 0; j < 19; j++) { + if (board[i][j] != 0){ + bfs(j, i); + } + } + } + System.out.println(0); + } +} \ No newline at end of file diff --git "a/changyeop/\353\260\261\354\244\200_2866_G5.java" "b/changyeop/\353\260\261\354\244\200_2866_G5.java" new file mode 100644 index 0000000..c3a3cc9 --- /dev/null +++ "b/changyeop/\353\260\261\354\244\200_2866_G5.java" @@ -0,0 +1,50 @@ +package changyeop; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +class Main2866 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int r = Integer.parseInt(st.nextToken()); + int c = Integer.parseInt(st.nextToken()); + + char[][] table = new char[r][c]; + for(int i = 0; i < r; i++){ + String cur = br.readLine(); + for(int j = 0; j < c; j++){ + table[i][j] = cur.charAt(j); + } + } + + String[] sums = new String[c]; + for(int i = 0; i < c; i++){ + String result = ""; + for(int j = 0; j < r; j++){ + result += table[j][i]; + } + sums[i] = result; + } + int answer = 0; + while(sums[0].length() > 0){ + boolean isSame = false; + for(int i = 0; i < sums.length; i++){ + sums[i] = sums[i].substring(1); + } + Arrays.sort(sums); + for(int i = 1; i < sums.length; i++){ + if(sums[i].equals(sums[i-1])){ + isSame = true; + break; + } + } + if (isSame) break; + answer++; + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" new file mode 100644 index 0000000..a1cccaf --- /dev/null +++ "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" @@ -0,0 +1,51 @@ +from collections import deque + +def bfs(cur): + p = [] + for r in range(5): + for c in range(5): + if cur[r][c] == 'P': + p.append([r, c]) + + dx = [0, 0, -1, 1] + dy = [-1, 1, 0, 0] + for s in p: + dq = deque() + dq.append(s) + visited = [[False] * 5 for _ in range(5)] + distance = [[0] * 5 for _ in range(5)] + visited[s[0]][s[1]] = True + + while dq: + y, x = dq.popleft() + visited[y][x] = True + for i in range(4): + nx, ny = x + dx[i], y + dy[i] + if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: + continue + if visited[ny][nx] == True: + continue + if cur[ny][nx] == 'X': + continue + distance[ny][nx] = distance[y][x] + 1 + if cur[ny][nx] == 'P' and distance[ny][nx] < 3: + return 0 + dq.append([ny, nx]) + + return 1 + + +def solution(places): + answer = [] + + for place in places: + cur = [] + for row in place: + cur.append(list(row)) + # print(cur) + result = bfs(cur) + answer.append(result) + + return answer + +print(solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]])) \ No newline at end of file diff --git "a/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" new file mode 100644 index 0000000..41f9bd4 --- /dev/null +++ "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" @@ -0,0 +1,39 @@ +import math +answer = math.inf + +def solution(begin, target, words): + + + visited = [0] * len(words) + + def find_next(cur, next): + cnt = 0 + for i in range(len(next)): + if cur[i] != next[i]: + cnt+=1 + if cnt == 1: + return True + else: + return False + + def dfs(cur, count): + + global answer + + if cur == target: + answer = min(answer, count) + return + if count > answer: + return + + for i in range(len(words)): + if visited[i] == 0 and find_next(cur, words[i]): + visited[i] = 1 + dfs(words[i], count+1) + visited[i] = 0 + + dfs(begin, 0) + + return 0 if answer == math.inf else answer + +print(solution('hit', 'cog', ["hot", "dot", "dog", "lot", "log"])) \ No newline at end of file diff --git "a/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" new file mode 100644 index 0000000..0c626e2 --- /dev/null +++ "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" @@ -0,0 +1,38 @@ +""" +가중치가 있는 간선을 연결할 때 최소비용 -> 크루스칼 알고리즘 +""" +def getParent(parents, node): + if parents[node] == node: + return node + else: + return getParent(parents, parents[node]) + +def patchParent(parents, start, end): + x = getParent(parents, start) + y = getParent(parents, end) + parents[x] = parents[y] = min(x, y) + +def isCycle(parents, start, end): + # 부모 노드를 더 작은 숫자의 노드로 바꾼다 + s = getParent(parents, start) + e = getParent(parents, end) + if s == e: + return True + else: + return False + +def solution(n, costs): + answer = 0 + costs.sort(key=lambda x:x[2]) + parents = [i for i in range(n)] + count = 0 + + for cur in costs: + if not isCycle(parents, cur[0], cur[1]): + answer += cur[2] + patchParent(parents, cur[0], cur[1]) + count += 1 + if count == n-1: + break + + return answer \ No newline at end of file diff --git "a/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" new file mode 100644 index 0000000..a604b37 --- /dev/null +++ "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" @@ -0,0 +1,21 @@ +""" +A와 B를 각각 정렬 -> 처음 정렬된 배열을 돌면서 result 계산 -> 첫번째 원소를 마지막으로 옮기며 result를 계산하고 작은 값이 나오면 반복 종료 +오름차순으로 정렬하면 시간초과가 난다. +내림차순으로 해서 그리디하게 풀어야 됨 +""" + +def solution(A, B): + answer = 0 + A.sort(reverse = True) + B.sort(reverse = True) + + for i in range(len(A)): + if A[i] < B[0]: + answer += 1 + del B[0] + else: + continue + + return answer + +print(solution([5,1,3,7], [2,2,6,8])) \ No newline at end of file diff --git "a/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" new file mode 100644 index 0000000..7598987 --- /dev/null +++ "b/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" @@ -0,0 +1,54 @@ +""" +재귀를 이용한 완탐으로 풀어보자 +""" + +maxDiff = 0 +answer = [-1] + +def moreSmall(ryan, answer): + for i in range(len(ryan)-1, 0, -1): + print(i) + if answer[i] < ryan[i]: + return True + elif answer[i] > ryan[i]: + return False + +def calScore(apeach, ryan): + global maxDiff, answer + apeachScore, ryanScore = 0, 0 + for i in range(len(apeach)): + if apeach[i] < ryan[i]: + ryanScore += (10-i) + elif apeach[i] > 0: + apeachScore += (10-i) + # 결과값이 max 값과 같다면 작은 점수를 많이 쏜 것을 결정 + curDiff = ryanScore - apeachScore + if curDiff > 0 and curDiff >= maxDiff: + if maxDiff == curDiff and not moreSmall(ryan, answer): + return + answer = ryan[:] + maxDiff = curDiff + +def recur(apeach, ryan, idx, arrows): + # end point + if idx > 10 or arrows == 0: + # 점수계산으로 넘어가기 + ryan[10] += arrows + calScore(apeach, ryan) + ryan[10] -= arrows + return + # 해당 점수를 얻는다면 + if apeach[idx] < arrows: + ryan[idx] = apeach[idx] + 1 + recur(apeach, ryan, idx+1, arrows-ryan[idx]) + ryan[idx] = 0 + # 해당 점수를 얻지 않는다면 + recur(apeach, ryan, idx+1, arrows) + +def solution(n, info): + global answer + ryan = [0] * 11 + recur(info, ryan, 0, n) + return answer + +print(solution(9, [0,0,1,2,0,1,1,1,1,1,1])) \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/.gitignore b/out/production/algorithm-study/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/out/production/algorithm-study/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/out/production/algorithm-study/.idea/algorithm-study.iml b/out/production/algorithm-study/.idea/algorithm-study.iml new file mode 100644 index 0000000..f392c3c --- /dev/null +++ b/out/production/algorithm-study/.idea/algorithm-study.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/kotlinc.xml b/out/production/algorithm-study/.idea/kotlinc.xml new file mode 100644 index 0000000..0dd4b35 --- /dev/null +++ b/out/production/algorithm-study/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/libraries/KotlinJavaRuntime.xml b/out/production/algorithm-study/.idea/libraries/KotlinJavaRuntime.xml new file mode 100644 index 0000000..a209aee --- /dev/null +++ b/out/production/algorithm-study/.idea/libraries/KotlinJavaRuntime.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/misc.xml b/out/production/algorithm-study/.idea/misc.xml new file mode 100644 index 0000000..dda7141 --- /dev/null +++ b/out/production/algorithm-study/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/modules.xml b/out/production/algorithm-study/.idea/modules.xml new file mode 100644 index 0000000..7499006 --- /dev/null +++ b/out/production/algorithm-study/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/.idea/vcs.xml b/out/production/algorithm-study/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/out/production/algorithm-study/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/out/production/algorithm-study/README.md b/out/production/algorithm-study/README.md new file mode 100644 index 0000000..3eaf45c --- /dev/null +++ b/out/production/algorithm-study/README.md @@ -0,0 +1,13 @@ +# Software Algorithm Study + + +## 문제 규칙 + +- 일주일에 최소 5문제를 푼다 +- 문제 난이도는 백준 실버 2 이상, 프로그래머스 level 2 이상만 인정 + + +## PR 규칙 +- 개인 branch를 판 후 main branch로 PR을 날린다 +- 개인 폴더에 코드파일을 추가한다 +- 일주일에 한번 PR을 날려 서로 확인을 받는다 (PR 마감 기한 월요일 06:00 AM) \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/BST.py b/out/production/algorithm-study/changyeop/BST.py new file mode 100644 index 0000000..89d3aba --- /dev/null +++ b/out/production/algorithm-study/changyeop/BST.py @@ -0,0 +1,68 @@ +from re import T + + +class Node: + def __init__(self, val) -> None: + self.val = val + self.left = None + self.right = None + pass + +class BST: + def __init__(self, root: Node) -> None: + self.root = root + + def insert(self, val): + self.root = self._insert_value(self.root, val=val) + return self.root is not None + + def _insert_value(self, node, val): + if node is None: + node = Node(val) + else: + if val <= node.val: + node.left = self._insert_value(node.left, val) + else: + node.right = self._insert_value(node.right,val) + return node + + def search(self, val): + return self._search_value(self.root, val) + + def _search_value(self, root, val): + if root is None or root.val == val: + return root is not None + elif val < root.val: + return self._search_value(root.left, val) + else: + return self._search_value(root.right, val) + + def delete(self, val): + self.root, is_deleted = self._delete_value(self.root, val) + return is_deleted + + def _delete_value(self, node, val): + if node is None: + return node, False + + is_deleted = False + if node.val == val: + is_deleted = True + if node.left and node.right: + parent, child = node, node.right + while child.left is not None: + parent, child = child, child.left + child.left = node.left + if parent != node: + parent.left = child.right + child.right = node.right + node = child + elif node.left or node.right: + node = node.left or node.right + else: + node = None + elif val < node.val: + node.left, is_deleted = self._delete_value(node.left, val) + else: + node.right, is_deleted = self._delete_value(node.right, val) + return node, is_deleted \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/BubbleSort.py b/out/production/algorithm-study/changyeop/BubbleSort.py new file mode 100644 index 0000000..b8c103c --- /dev/null +++ b/out/production/algorithm-study/changyeop/BubbleSort.py @@ -0,0 +1,8 @@ +from typing import List + + +def bubble(arr: List[int]): + for i in range(len(arr) - 1, 0, -1): + for j in range(i): + if arr[j] > arr[j+1]: + arr[j], arr[j+1] = arr[j+1], arr[j] \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/CircularQueue.py b/out/production/algorithm-study/changyeop/CircularQueue.py new file mode 100644 index 0000000..4a17f29 --- /dev/null +++ b/out/production/algorithm-study/changyeop/CircularQueue.py @@ -0,0 +1,34 @@ +class MyCircularQueue: + def __init__(self, k: int) -> None: + self.q = [None] * k + self.maxLen = k + self.p1 = 0 # front + self.p2 = 0 # rear + + def enqueue(self, value: int): + if self.q[self.p2] is None: + self.q[self.p2] = value + self.p2 = (self.p2 + 1) % self.maxLen + return True + else: + return False + + def dequeue(self): + if self.q[self.p1] is None: + return False + else: + self.q[self.p1] = None + self.p1 = (self.p1 + 1) % self.maxLen + return True + + def Front(self): + return -1 if self.q[self.p1] is None else self.q[self.p1] + + def Rear(self): + return -1 if self.q[self.p2 - 1] is None else self.q[self.p2 - 1] + + def isEmpty(self): + return self.p1 == self.p2 and self.q[self.p1] is None + + def isFull(self): + return self.p1 == self.p2 and self.q[self.p1] is not None \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/Combination.py b/out/production/algorithm-study/changyeop/Combination.py new file mode 100644 index 0000000..a02fc4e --- /dev/null +++ b/out/production/algorithm-study/changyeop/Combination.py @@ -0,0 +1,15 @@ +def combine(n: int, k: int): + result = [] + + def dfs(items, start: int, k: int): + if k == 0: + result.append(items[:]) + return + + for i in range(start, n+1): + items.append(i) + dfs(items, i+1, k-1) + items.pop() + dfs([], 1, k) + + return result \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/CombinationSum.py b/out/production/algorithm-study/changyeop/CombinationSum.py new file mode 100644 index 0000000..55b0845 --- /dev/null +++ b/out/production/algorithm-study/changyeop/CombinationSum.py @@ -0,0 +1,18 @@ +from typing import List + + +def combinationSum(candidates: List[int], target: int): + result = [] + + def dfs(cur_sum, index, path): + if cur_sum > target: + return + if cur_sum == target: + result.append(path[:]) + return + + for i in range(index, len(candidates)): + dfs(cur_sum+candidates[i], i, path+[candidates[i]]) + + dfs(target, 0, []) + return result \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/HeapSort.py b/out/production/algorithm-study/changyeop/HeapSort.py new file mode 100644 index 0000000..5d4a348 --- /dev/null +++ b/out/production/algorithm-study/changyeop/HeapSort.py @@ -0,0 +1,21 @@ +def heapify(li, index, n): + l = index * 2 + 1 + r = index * 2 + 2 + s_idx = index + if l <= n and li[s_idx] > li[l]: + s_idx = l + if r <= n and li[s_idx] > li[r]: + s_idx = r + if s_idx != index: + li[index], li[s_idx] = li[s_idx], li[index] + return heapify(li, s_idx, n) +def heap_sort(arr): + n = len(arr) + + for i in range(n // 2 - 1, -1, -1): + heapify(arr, i, n) + + for i in range(n-1, 0, -1): + arr[0], arr[i] = arr[i], arr[0] + heapify(arr, 0, i) + return arr \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/InsertionSort.py b/out/production/algorithm-study/changyeop/InsertionSort.py new file mode 100644 index 0000000..d5ebb62 --- /dev/null +++ b/out/production/algorithm-study/changyeop/InsertionSort.py @@ -0,0 +1,5 @@ +def insertion(arr): + for end in range(1, len(arr)): + for i in range(end, 0, -1): + if arr[i-1] > arr[i]: + arr[i-1], arr[i] = arr[i], arr[i-1] \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/Leet_3_M.py b/out/production/algorithm-study/changyeop/Leet_3_M.py new file mode 100644 index 0000000..e6ff990 --- /dev/null +++ b/out/production/algorithm-study/changyeop/Leet_3_M.py @@ -0,0 +1,17 @@ +def lengthOfLongestSubstring(s: str) -> int: + # add char -> if appear contained char -> make new string : 'dvdf' 경우 틀림 + answer = 0 + output = '' + for c in s: + if c in output: + # make new string + start = output.index(c) + output = output[start+1:] + output += c + else: + output += c + answer = max(answer, len(output)) + + return answer + +print(lengthOfLongestSubstring(s='dvdf')) \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/LongestSubstring.py b/out/production/algorithm-study/changyeop/LongestSubstring.py new file mode 100644 index 0000000..f6f7f27 --- /dev/null +++ b/out/production/algorithm-study/changyeop/LongestSubstring.py @@ -0,0 +1,10 @@ +def lengthOfSubstring(s: str): + used = {} + maxLen, start = 0, 0 + for index, char in enumerate(s): + if char in used and start <= used[char]: + start = used[char] + 1 + else: + maxLen = max(maxLen, index - start + 1) + used[char] = index + return maxLen \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/Main.class b/out/production/algorithm-study/changyeop/Main.class new file mode 100644 index 0000000..b4df2ce Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main.class differ diff --git a/out/production/algorithm-study/changyeop/Main1092.class b/out/production/algorithm-study/changyeop/Main1092.class new file mode 100644 index 0000000..1110445 Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main1092.class differ diff --git a/out/production/algorithm-study/changyeop/Main11000.class b/out/production/algorithm-study/changyeop/Main11000.class new file mode 100644 index 0000000..180fd0f Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main11000.class differ diff --git a/out/production/algorithm-study/changyeop/Main12933.class b/out/production/algorithm-study/changyeop/Main12933.class new file mode 100644 index 0000000..f33a9ab Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main12933.class differ diff --git a/out/production/algorithm-study/changyeop/Main16926.class b/out/production/algorithm-study/changyeop/Main16926.class new file mode 100644 index 0000000..824ed48 Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main16926.class differ diff --git a/out/production/algorithm-study/changyeop/Main1715.class b/out/production/algorithm-study/changyeop/Main1715.class new file mode 100644 index 0000000..09cfa2e Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main1715.class differ diff --git a/out/production/algorithm-study/changyeop/Main2212.class b/out/production/algorithm-study/changyeop/Main2212.class new file mode 100644 index 0000000..c3c9870 Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main2212.class differ diff --git a/out/production/algorithm-study/changyeop/Main2252.class b/out/production/algorithm-study/changyeop/Main2252.class new file mode 100644 index 0000000..f5ce9de Binary files /dev/null and b/out/production/algorithm-study/changyeop/Main2252.class differ diff --git a/out/production/algorithm-study/changyeop/MergeSort.py b/out/production/algorithm-study/changyeop/MergeSort.py new file mode 100644 index 0000000..05e728f --- /dev/null +++ b/out/production/algorithm-study/changyeop/MergeSort.py @@ -0,0 +1,22 @@ +def merge_sort(arr): + + if len(arr) < 2: + return arr + + mid = len(arr) // 2 + low_arr = merge_sort(arr[:mid]) + high_arr = merge_sort(arr[mid:]) + + merged_arr = [] + + l = h = 0 + while l < len(low_arr) and h < len(high_arr): + if low_arr[l] < high_arr[h]: + merged_arr.append(low_arr[l]) + l += 1 + else: + merged_arr.append(high_arr[h]) + h += 1 + merged_arr += low_arr[l:] + merged_arr += low_arr[:h] + return merged_arr \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/MostCommonWord.py b/out/production/algorithm-study/changyeop/MostCommonWord.py new file mode 100644 index 0000000..4859d1c --- /dev/null +++ b/out/production/algorithm-study/changyeop/MostCommonWord.py @@ -0,0 +1,9 @@ +from collections import Counter +import re +from typing import List + + +def solution(paragraph: str, banned: List[str]): + words = [w for w in re.sub(r'[^\w]', ' ', paragraph).lower().split() if w not in banned] + counts = Counter(words) + return counts.most_common(1)[0][0] diff --git a/out/production/algorithm-study/changyeop/Permutation.py b/out/production/algorithm-study/changyeop/Permutation.py new file mode 100644 index 0000000..d278ddd --- /dev/null +++ b/out/production/algorithm-study/changyeop/Permutation.py @@ -0,0 +1,21 @@ +from typing import List + + +def permute(nums: List[int]): + result = [] + perm = [] + + def dfs(items): + if len(items) == 0: + result.append(perm[:]) + return + for i in items: + next_items = items[:] + next_items.remove(i) + perm.append(i) + dfs(next_items) + perm.pop() + + dfs(nums) + + return result diff --git a/out/production/algorithm-study/changyeop/QueueByStack.py b/out/production/algorithm-study/changyeop/QueueByStack.py new file mode 100644 index 0000000..c92580b --- /dev/null +++ b/out/production/algorithm-study/changyeop/QueueByStack.py @@ -0,0 +1,20 @@ +class MyQueue: + def __init__(self) -> None: + self.input = [] + self.output = [] + + def push(self, x): + self.input.append(x) + + def peek(self): + if not self.output: + while self.input: + self.output.append(self.input.pop()) + return self.output[-1] + + def pop(self): + self.peek() + return self.output.pop() + + def empty(self): + return self.input == [] and self.output == [] \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/QuickSort.py b/out/production/algorithm-study/changyeop/QuickSort.py new file mode 100644 index 0000000..96f73b6 --- /dev/null +++ b/out/production/algorithm-study/changyeop/QuickSort.py @@ -0,0 +1,14 @@ +def quick_sort(arr): + if len(arr) <= 1: + return arr + + pivot = arr[len(arr) // 2] + min_arr, equal_arr, max_arr = [], [], [] + for num in arr: + if num < pivot: + min_arr.append(num) + elif num > pivot: + max_arr.append(num) + else: + equal_arr.append(num) + return quick_sort(min_arr) + equal_arr + quick_sort(max_arr) \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/RemoveDuplicateLetters.py b/out/production/algorithm-study/changyeop/RemoveDuplicateLetters.py new file mode 100644 index 0000000..38bc4fd --- /dev/null +++ b/out/production/algorithm-study/changyeop/RemoveDuplicateLetters.py @@ -0,0 +1,24 @@ +# by recur +from collections import Counter + + +def removeDuplicateLetters(s: str): + for char in sorted(set(s)): + suffix = s[s.index(char):] + if set(s) == set(suffix): + return char + removeDuplicateLetters(suffix.replace(char, '')) + return '' + +def byStack(s: str): + counter, seen, stack = Counter(s), set(), [] + for char in s: + counter[char] -= 1 + if char in seen: + #이미 처리된 문자는 스킵 + continue + while stack and char < stack[-1] and counter[stack[-1]] > 0: + seen.remove(stack.pop()) + stack.append(char) + seen.add(char) + + return ''.join(stack) \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/ReverseList.py b/out/production/algorithm-study/changyeop/ReverseList.py new file mode 100644 index 0000000..7e6e658 --- /dev/null +++ b/out/production/algorithm-study/changyeop/ReverseList.py @@ -0,0 +1,29 @@ +class ListNode: + def __init__(self, val = 0, next = None) -> None: + self.val = val + self.next = next +class Solution: + def solution(head: ListNode): + + + #반복문 + node, prev = head, None + + while node: + next, node.next = node.next, prev + prev, node = node, next + + return prev + + + # 재귀풀이 + def reverse(node: ListNode, prev: ListNode = None): + if not node: + return prev + next, node.next = node.next, prev + + return reverse(next, node) + + return reverse(head) + + \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/SelectionSort.py b/out/production/algorithm-study/changyeop/SelectionSort.py new file mode 100644 index 0000000..46056cf --- /dev/null +++ b/out/production/algorithm-study/changyeop/SelectionSort.py @@ -0,0 +1,7 @@ +def selection(arr): + for i in range(len(arr) -1): + min_idx = i + for j in range(i+1, len(arr)): + if arr[j] < arr[min_idx]: + min_idx = j + arr[i], arr[min_idx] = arr[min_idx], arr[i] \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/Solution.class b/out/production/algorithm-study/changyeop/Solution.class new file mode 100644 index 0000000..1ba7f4e Binary files /dev/null and b/out/production/algorithm-study/changyeop/Solution.class differ diff --git a/out/production/algorithm-study/changyeop/StackByQueue.py b/out/production/algorithm-study/changyeop/StackByQueue.py new file mode 100644 index 0000000..eba684c --- /dev/null +++ b/out/production/algorithm-study/changyeop/StackByQueue.py @@ -0,0 +1,20 @@ +import collections + + +class StackByQueue: + def __init__(self) -> None: + self.q = collections.deque() + + def push(self, x): + self.q.append(x) + for _ in range(len(self.q)-1): + self.q.append(self.q.popleft()) + + def pop(self): + return self.q.popleft() + + def top(self): + return self.q[0] + + def empty(self): + return len(self.q) == 0 \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/TwoSum.py b/out/production/algorithm-study/changyeop/TwoSum.py new file mode 100644 index 0000000..9cd59e7 --- /dev/null +++ b/out/production/algorithm-study/changyeop/TwoSum.py @@ -0,0 +1,23 @@ +from typing import List + + +def solution(nums: List[str], target: int): + nums_map = {} + for i, num in enumerate(nums): + nums_map[num] = i + + for i, num in enumerate(nums): + if target - num in nums_map and i != nums_map[target - num]: + return nums.index(num), nums_map[target - num] + + # 투 포인터 + nums.sort() # 인덱스를 찾는 문제라면 정렬하면 안된다. + left, right = 0, len(nums) - 1 + while not left == right: + if nums[left] + nums[right] < target: + left += 1 + elif nums[left] + nums[right] > target: + right -= 1 + else: + return left, right + \ No newline at end of file diff --git a/out/production/algorithm-study/changyeop/ValidPalindrome.py b/out/production/algorithm-study/changyeop/ValidPalindrome.py new file mode 100644 index 0000000..6da4f7d --- /dev/null +++ b/out/production/algorithm-study/changyeop/ValidPalindrome.py @@ -0,0 +1,34 @@ +from collections import deque +from curses.ascii import isalnum +import re + + +def useList(s: str): + strs = [] + for char in s: + if char.isalnum(): + strs.append(char.lower()) + while len(strs) > 1: + if strs.pop(0) != strs.pop(): # pop(0)의 시간복잡도는 O(n) + return False + + return True + +# 데크 자료형을 사용 +def useDeque(s: str): + strs = deque() + for char in s: + if char.isalnum(): + strs.append(char.lower()) + + while len(strs) > 1: + if strs.popleft() != strs.pop(): # popleft 의 시간복잡도는 O(1) + return False + + return True + +# 슬라이싱을 활용한 경우 +def useSlicing(s: str): + s = s.lower() + s = re.sub('[^a-z0-9]', '', s) # 소문자와 숫자가 아닌 문자들을 ''로 치환한다 + return s == s[::-1] \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_1025_G5.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_1025_G5.py" new file mode 100644 index 0000000..3e122ec --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_1025_G5.py" @@ -0,0 +1,46 @@ +import math +import sys +from tokenize import String + + +n, m = map(int, sys.stdin.readline().split()) +board = [] +answer = -1 + +def isPowered(str): + n = int(str) + if math.pow(int(math.sqrt(n)), 2) == n: + return True + else: + return False + +def makeNum(i, j, y, x, str): + + cur = str + board[i][j] + global answer + + if isPowered(cur): + answer = max(answer, int(cur)) + + if isPowered(cur[::-1]): + answer = max(answer, int(cur[::-1])) + + if y == 0 and x == 0: + return + + if i + y >= n or j + x >= m or j + x < 0: + return + + makeNum(i+y, j+x, y, x, cur) + +for i in range(n): + board.append(list(sys.stdin.readline().strip())) +# print(board) +for i in range(n): + for j in range(m): + for y in range(n): + for x in range(m): + makeNum(i, j, y, x, '') # 좌상우하 대각선 + makeNum(i, j, y, -x, '') # 우상좌하 대각선 + +print(answer) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_20207_\353\213\254\353\240\245_S1.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_20207_\353\213\254\353\240\245_S1.py" new file mode 100644 index 0000000..4bb3f7e --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_20207_\353\213\254\353\240\245_S1.py" @@ -0,0 +1,26 @@ +import sys + +n = int(sys.stdin.readline()) +calender = [0 for _ in range(366)] + +for i in range(n): + s, e = map(int, sys.stdin.readline().split()) + for j in range(s, e+1): + calender[j] += 1 # depth를 기록해 나간다 + +# 코팅지 넓이 계산 +height = 0 +width = 0 +size = 0 +for i in range(len(calender)): + if calender[i] != 0: + height = max(height, calender[i]) + width += 1 + else: + size += width * height + width = 0 + height = 0 +# 365일에 일정이 있는 경우 +size += width * height + +print(size) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2110_\352\263\265\354\234\240\352\270\260_G4.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2110_\352\263\265\354\234\240\352\270\260_G4.py" new file mode 100644 index 0000000..a848a86 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2110_\352\263\265\354\234\240\352\270\260_G4.py" @@ -0,0 +1,45 @@ +""" +가장 인접한 두 공유기 사이의 거리를 최대로 한다 +""" +import sys + + +n, c = map(int, sys.stdin.readline().strip().split()) +houses = [0] * n +# print(houses) +for i in range(n): + houses[i] = int(sys.stdin.readline()) + +houses = sorted(houses) + +# 공유기 사이의 최소 거리가 가장 먼 경우는 일정한 간격으로 배치되었을 떄 +# 초기 거리를 반으로 잡고 이분탐색 +minLen = 1 +maxLen = houses[n-1] - houses[0] +answer = 0 + +# 무조건 양 끝에 공유기 하나씩 배치 +if c == 2: + print(maxLen) + sys.exit(0) + +while minLen <= maxLen : + mid = (maxLen + minLen) // 2 + cnt = 2 + prevHouse = houses[0] + for i in range(1, n-1): + left, right = houses[i] - prevHouse, houses[n-1] - houses[i] + cur = min(left, right) + if cur >= mid: + cnt+=1 + prevHouse = houses[i] + + if cnt >= c: + answer = max(answer, mid) + minLen = mid +1 + continue + + if cnt < c: + maxLen = mid - 1 + +print(answer) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2141_\354\232\260\354\262\264\352\265\255_G4.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2141_\354\232\260\354\262\264\352\265\255_G4.py" new file mode 100644 index 0000000..1a2f328 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_2141_\354\232\260\354\262\264\352\265\255_G4.py" @@ -0,0 +1,25 @@ +import sys +# 단순히 이중for문을 사용하는 접근법 : 시간초과 + +n = int(sys.stdin.readline()) +towns = [] +people = 0 + +for i in range(n): + x, a = map(int, sys.stdin.readline().strip().split()) + towns.append([x, a]) + people += a +# print(towns) + +towns.sort(key=lambda x: x[0]) + +# 해당 마을의 왼쪽과 오른쪽의 사람 수가 비슷해야한다 +# 전체 사람 수를 구하고, 마을을 돌면서 왼쪽 사람수를 뺐을 때 전체의 절반이 넘어가는 순간을 찾는다 +left = 0 +for i in range(len(towns)): + left += towns[i][1] + if left >= people/2: + answer = towns[i][0] + break + +print(answer) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_21921_S3.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_21921_S3.py" new file mode 100644 index 0000000..22d98c3 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_21921_S3.py" @@ -0,0 +1,25 @@ +import sys +n, x = map(int, sys.stdin.readline().split(' ')) +# print(n,x) +arr = list(map(int, sys.stdin.readline().split(' '))) +# print(arr) +end = x +res = 0 +for i in range(end): + res += arr[i] +maxRes = res +cnt = 1 +for i in range(end, n, 1): + start = i - x + res = res + arr[i] - arr[start] + if res > maxRes: + maxRes = res + cnt = 1 + elif res == maxRes: + cnt += 1 + +if maxRes == 0: + print('SAD') +else: + print(maxRes) + print(cnt) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_22944_\354\243\275\354\235\214\354\235\230\353\271\204_G4.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_22944_\354\243\275\354\235\214\354\235\230\353\271\204_G4.py" new file mode 100644 index 0000000..fe53ed8 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_22944_\354\243\275\354\235\214\354\235\230\353\271\204_G4.py" @@ -0,0 +1,50 @@ +import sys + + +n, h, d = map(int, sys.stdin.readline().split()) +land = [] +startX, startY = 0, 0 +for i in range(n): + cur = sys.stdin.readline().strip() + land.append(list(cur)) + if 'S' in cur: + # print(cur.index('S'), i) + startY, startX = i, cur.index('S') +moveX = [0, 0, -1, 1] # 상하좌우 +moveY = [-1, 1, 0, 0] +# 안전지대로 이동할 때의 최소이동횟수를 구한다 +# 이동하기 전 우산을 쓰고 있는지 체크하고 먼저 우산체력부터 -1 + +visited = [[0] * n for _ in range(n)] # 방문체크 +q = [[startY, startX, h, 0, 0]] # 각 격자에서의 상태값을 한번에 체크 +visited[startY][startX] = h + +while q: + r, c, curh, curu, cnt = q.pop(0) + # print(r, c) + # 먼저 큐에 넣은 뒤에 판단하지 말고, 판단한 뒤 큐에 넣자 + for i in range(4): + nr = r + moveY[i] + nc = c + moveX[i] + if nr < 0 or nr >= n or nc < 0 or nc >= n: + continue + if land[nr][nc] == 'E': + print(cnt+1) + sys.exit(0) + nh, nu = curh, curu + # 우산이 있다면 + if land[nr][nc] == 'U': + nu = d + # 비가 오는 곳이라면 + if nu == 0: + nh -= 1 + else: + nu -= 1 + if nh == 0: + continue + + if visited[nr][nc] < nh: + # 더 많은 체력으로 갈 수 있다면 추가 + visited[nr][nc] = nh + q.append([nr, nc, nh, nu, cnt+1]) +print(-1) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\353\257\274\352\262\270\354\210\230_S2.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\353\257\274\352\262\270\354\210\230_S2.py" new file mode 100644 index 0000000..51d1261 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\353\257\274\352\262\270\354\210\230_S2.py" @@ -0,0 +1,28 @@ +""" +문자열의 길이 <= 3000 -> 숫자로 대수비교하면 안된다 +최댓값 : M과 K를 하나의 그룹으로 10진수를 만들 때 +최솟값 : M과 K를 나눌 때 +""" + +import sys + +str = sys.stdin.readline().strip() + +max, min = "", "" +cntM = 0 + +for s in str: + # print(s) + if s == 'M': + cntM+=1 + continue + # K가 나왔을 때 + max += '5' + '0' * cntM + min += '1' + '0' * (cntM-1) + '5' if cntM != 0 else '5' + cntM = 0 + +if cntM != 0: + max += '1' * (cntM) + min += '1' + '0' * (cntM-1) +print(max) +print(min) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220_G5.py" "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220_G5.py" new file mode 100644 index 0000000..94b1764 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\353\260\261\354\244\200_\355\226\211\353\263\265\354\234\240\354\271\230\354\233\220_G5.py" @@ -0,0 +1,35 @@ +""" +k 그룹으로 나눈다 -> k-1 개의 경계를 만들어야 한다. +가장 차이가 큰 숫자 사이에 경계를 만들면 최대이득이다. +=> 그 차이만큼 최종값에서 사라지고 0이 된다 +""" + + +import sys + + +n, k = map(int, sys.stdin.readline().strip().split()) +student = list(map(int, sys.stdin.readline().strip().split())) +# print(student) +answer = 0 + +if n == k: + print(answer) + sys.exit(0) + +# 초기값 설정 +answer = student[len(student)-1] - student[0] +diff = [] +for i in range(len(student)-1): + diff.append(student[i+1]-student[i]) + +diff = sorted(diff) +diff.reverse() + +for i in diff: + if k == 1: + break + answer -= i + k -= 1 + +print(answer) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" new file mode 100644 index 0000000..a1cccaf --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\352\261\260\353\246\254\353\221\220\352\270\260\355\231\225\354\235\270\355\225\230\352\270\260_Lv3.py" @@ -0,0 +1,51 @@ +from collections import deque + +def bfs(cur): + p = [] + for r in range(5): + for c in range(5): + if cur[r][c] == 'P': + p.append([r, c]) + + dx = [0, 0, -1, 1] + dy = [-1, 1, 0, 0] + for s in p: + dq = deque() + dq.append(s) + visited = [[False] * 5 for _ in range(5)] + distance = [[0] * 5 for _ in range(5)] + visited[s[0]][s[1]] = True + + while dq: + y, x = dq.popleft() + visited[y][x] = True + for i in range(4): + nx, ny = x + dx[i], y + dy[i] + if nx < 0 or nx >= 5 or ny < 0 or ny >= 5: + continue + if visited[ny][nx] == True: + continue + if cur[ny][nx] == 'X': + continue + distance[ny][nx] = distance[y][x] + 1 + if cur[ny][nx] == 'P' and distance[ny][nx] < 3: + return 0 + dq.append([ny, nx]) + + return 1 + + +def solution(places): + answer = [] + + for place in places: + cur = [] + for row in place: + cur.append(list(row)) + # print(cur) + result = bfs(cur) + answer.append(result) + + return answer + +print(solution([["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"], ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"], ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"], ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"], ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\204\244\355\212\270\354\233\214\355\201\254_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\204\244\355\212\270\354\233\214\355\201\254_Lv3.py" new file mode 100644 index 0000000..ec64e0b --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\204\244\355\212\270\354\233\214\355\201\254_Lv3.py" @@ -0,0 +1,25 @@ +""" +bfs로 방문이력 검사하면서 인접 노드를 체크한다. +""" + +def solution(n, computers): + answer = 0 + visited = [0 for _ in range(n)] + + for i in range(n): + if visited[i] == 1: + continue + visited[i] = 1 + q = [i] + while q: + cur = q.pop(0) + for j in range(n): + if computers[cur][j] and visited[j] == 0: + q.append(j) + visited[j] = 1 + answer += 1 + + + return answer + +print(solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\206\215\354\271\264\353\251\224\353\235\274_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\206\215\354\271\264\353\251\224\353\235\274_Lv3.py" new file mode 100644 index 0000000..6a1553e --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\206\215\354\271\264\353\251\224\353\235\274_Lv3.py" @@ -0,0 +1,20 @@ +""" +[0] 기준으로 정렬 -> 차량의 개수가 100000대 이하라서 이중for문 + 그리디로 풀어보자 +""" +def solution(routes): + answer = 0 + routes.sort(key=lambda x: x[1]) + # print(routes) + # 진출지점에 카메라를 설치한다 + # 뒤에 있는 차의 진입시점이 앞 차의 진입시점보다 빠르면 카운트하지 않는다 + end = -30001 + for i in range(len(routes)): + if routes[i][0] <= end: + continue + answer += 1 + end = routes[i][1] + + return answer + +print(solution([[-20,-15], [-14,-5], [-18,-13], [-5,-3]])) +print(solution([[-100,100],[50,170],[150,200],[-50,-10],[10,20],[30,40]])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" new file mode 100644 index 0000000..41f9bd4 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\213\250\354\226\264\353\263\200\355\231\230_Lv3.py" @@ -0,0 +1,39 @@ +import math +answer = math.inf + +def solution(begin, target, words): + + + visited = [0] * len(words) + + def find_next(cur, next): + cnt = 0 + for i in range(len(next)): + if cur[i] != next[i]: + cnt+=1 + if cnt == 1: + return True + else: + return False + + def dfs(cur, count): + + global answer + + if cur == target: + answer = min(answer, count) + return + if count > answer: + return + + for i in range(len(words)): + if visited[i] == 0 and find_next(cur, words[i]): + visited[i] = 1 + dfs(words[i], count+1) + visited[i] = 0 + + dfs(begin, 0) + + return 0 if answer == math.inf else answer + +print(solution('hit', 'cog', ["hot", "dot", "dog", "lot", "log"])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\251\224\353\211\264\353\246\254\353\211\264\354\226\274_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\251\224\353\211\264\353\246\254\353\211\264\354\226\274_Lv2.py" new file mode 100644 index 0000000..72ca1c4 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\251\224\353\211\264\353\246\254\353\211\264\354\226\274_Lv2.py" @@ -0,0 +1,29 @@ +from collections import Counter +from itertools import combinations + + +def solution(orders, course): + answer = [] + # sort order each element + for i in range(len(orders)): + orders[i] = ''.join(sorted(orders[i])) + # combination + # 모든 order에 대해 조합을 구하고, Counter로 같은 것들의 숫자를 센다 + for c in course: + cur = [] + for order in orders: + comb = combinations(order, c) + cur += comb + # print(cur) + cnt = Counter(cur) + # print(cnt) + if len(cnt) != 0 and max(cnt.values()) > 1: + for res in cnt: + if cnt[res] == max(cnt.values()): + answer.append(''.join(res)) + print(answer) + return sorted(answer) + +orders = ['ABCDE', 'AB', 'CD', 'ADE', 'XYZ', 'XYZ', 'ACD'] +course = [2, 3, 5] +print(solution(orders, course)) diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\263\264\354\204\235\354\207\274\355\225\221_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\263\264\354\204\235\354\207\274\355\225\221_Lv2.py" new file mode 100644 index 0000000..1c29400 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\353\263\264\354\204\235\354\207\274\355\225\221_Lv2.py" @@ -0,0 +1,36 @@ +from collections import Counter, defaultdict +# 매 반복마다 counter를 쓰면 시간초과 +# start = 0, end = len(gems)에서 시작하는 것은 최적의 답을 찾지 못한다 +def solution(gems): + + start, end = 0, 0 + answer = [start, len(gems)] + gem_len, gem_kinds = len(gems), len(set(gems)) + gem_dict = defaultdict(lambda: 0) # 구매하는 범위 안에 존재하는 보석 개수 + # left, right로 나눠서 하나씩 줄여가며 탐색 + while True: + # start를 기준으로 끝까지 탐색했을 때 종료 + if start == gem_len: + break; + cur_kinds = len(gem_dict) + # 모든 종류가 들어있다 + if cur_kinds == gem_kinds: + if end - start < answer[1] - answer[0]: + answer[0], answer[1] = start, end + gem_dict[gems[start]] -= 1 + if gem_dict[gems[start]] == 0: + del gem_dict[gems[start]] + start += 1 + continue + if end == gem_len: + break + if cur_kinds != gem_kinds: + gem_dict[gems[end]] += 1 + end += 1 + continue + + answer[0] += 1 + + return answer + +print(solution(['aaa', 'bbb', 'avsvd', 'asdfc', 'aaa'])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" new file mode 100644 index 0000000..0c626e2 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\204\254\354\227\260\352\262\260\355\225\230\352\270\260_Lv3.py" @@ -0,0 +1,38 @@ +""" +가중치가 있는 간선을 연결할 때 최소비용 -> 크루스칼 알고리즘 +""" +def getParent(parents, node): + if parents[node] == node: + return node + else: + return getParent(parents, parents[node]) + +def patchParent(parents, start, end): + x = getParent(parents, start) + y = getParent(parents, end) + parents[x] = parents[y] = min(x, y) + +def isCycle(parents, start, end): + # 부모 노드를 더 작은 숫자의 노드로 바꾼다 + s = getParent(parents, start) + e = getParent(parents, end) + if s == e: + return True + else: + return False + +def solution(n, costs): + answer = 0 + costs.sort(key=lambda x:x[2]) + parents = [i for i in range(n)] + count = 0 + + for cur in costs: + if not isCycle(parents, cur[0], cur[1]): + answer += cur[2] + patchParent(parents, cur[0], cur[1]) + count += 1 + if count == n-1: + break + + return answer \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" new file mode 100644 index 0000000..a604b37 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\210\253\354\236\220\352\262\214\354\236\204_Lv3.py" @@ -0,0 +1,21 @@ +""" +A와 B를 각각 정렬 -> 처음 정렬된 배열을 돌면서 result 계산 -> 첫번째 원소를 마지막으로 옮기며 result를 계산하고 작은 값이 나오면 반복 종료 +오름차순으로 정렬하면 시간초과가 난다. +내림차순으로 해서 그리디하게 풀어야 됨 +""" + +def solution(A, B): + answer = 0 + A.sort(reverse = True) + B.sort(reverse = True) + + for i in range(len(A)): + if A[i] < B[0]: + answer += 1 + del B[0] + else: + continue + + return answer + +print(solution([5,1,3,7], [2,2,6,8])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" new file mode 100644 index 0000000..7598987 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\226\221\352\266\201\353\214\200\355\232\214_Lv2.py" @@ -0,0 +1,54 @@ +""" +재귀를 이용한 완탐으로 풀어보자 +""" + +maxDiff = 0 +answer = [-1] + +def moreSmall(ryan, answer): + for i in range(len(ryan)-1, 0, -1): + print(i) + if answer[i] < ryan[i]: + return True + elif answer[i] > ryan[i]: + return False + +def calScore(apeach, ryan): + global maxDiff, answer + apeachScore, ryanScore = 0, 0 + for i in range(len(apeach)): + if apeach[i] < ryan[i]: + ryanScore += (10-i) + elif apeach[i] > 0: + apeachScore += (10-i) + # 결과값이 max 값과 같다면 작은 점수를 많이 쏜 것을 결정 + curDiff = ryanScore - apeachScore + if curDiff > 0 and curDiff >= maxDiff: + if maxDiff == curDiff and not moreSmall(ryan, answer): + return + answer = ryan[:] + maxDiff = curDiff + +def recur(apeach, ryan, idx, arrows): + # end point + if idx > 10 or arrows == 0: + # 점수계산으로 넘어가기 + ryan[10] += arrows + calScore(apeach, ryan) + ryan[10] -= arrows + return + # 해당 점수를 얻는다면 + if apeach[idx] < arrows: + ryan[idx] = apeach[idx] + 1 + recur(apeach, ryan, idx+1, arrows-ryan[idx]) + ryan[idx] = 0 + # 해당 점수를 얻지 않는다면 + recur(apeach, ryan, idx+1, arrows) + +def solution(n, info): + global answer + ryan = [0] * 11 + recur(info, ryan, 0, n) + return answer + +print(solution(9, [0,0,1,2,0,1,1,1,1,1,1])) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\240\204\355\231\224\353\262\210\355\230\270\353\252\251\353\241\235_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\240\204\355\231\224\353\262\210\355\230\270\353\252\251\353\241\235_Lv2.py" new file mode 100644 index 0000000..4d34252 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\240\204\355\231\224\353\262\210\355\230\270\353\252\251\353\241\235_Lv2.py" @@ -0,0 +1,9 @@ +def solution(phone_book): + phone_book.sort() + for i in range(len(phone_book)-1): + if phone_book[i] in phone_book[i+1] and phone_book[i+1].index(phone_book[i]) == 0: + return False + return True + +arr = ['123','456','78'] +print(solution(arr)) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\243\274\354\260\250\354\232\224\352\270\210\352\263\204\354\202\260_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\243\274\354\260\250\354\232\224\352\270\210\352\263\204\354\202\260_Lv2.py" new file mode 100644 index 0000000..a23723a --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\243\274\354\260\250\354\232\224\352\270\210\352\263\204\354\202\260_Lv2.py" @@ -0,0 +1,52 @@ +""" +입차한 후 출차 내역이 없다면 23:59에 출차한 것으로 판단 +누적 주차시간으로 요금 계산 +기본시간 이하라면 기본요금만. 초과한 시간에 대해서 단위 시간만다 단위 요금 +""" + +from collections import defaultdict +import math + + +def solution(fees, records): + defaultMin, defaultFee, unitTime, unitFee = fees[0], fees[1], fees[2], fees[3] + dict = {} # 현재 입차되어 있는 차의 번호와 시간 + result = defaultdict(int) # 차량 번호에 따라 누적 주차시간 기록 + for record in records: + info = record.split() + # print(info) + hour, minute = info[0].split(":") + time = int(hour) * 60 + int(minute) # tiemstamp 개념과 비슷하게 계산 + # print(time) + if info[1] in dict: + # print(dict.keys()) + # 입차되어 있다면 주차시간 기록 + result[info[1]] += time - dict[info[1]] + del dict[info[1]] + else: + dict[info[1]] = time + + # 나가지 않고 입차되어 있다면 + endTime = 23 * 60 + 59 + for number in dict.keys(): + # print(number) + result[number] += endTime - dict[number] + + answer = [] + for number, time in result.items(): + fee = 0 + if time <= defaultMin: + fee = defaultFee + else: + fee = defaultFee + math.ceil((time-defaultMin)/unitTime) * unitFee + answer.append((number, fee)) + answer.sort() + for i in range(len(answer)): + answer[i] = answer[i][1] + + return answer + +fees = [180, 5000, 10, 600] +records = ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] + +print(solution(fees, records)) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\247\225\352\262\200\353\213\244\353\246\254\352\261\264\353\204\210\352\270\260_Lv3.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\247\225\352\262\200\353\213\244\353\246\254\352\261\264\353\204\210\352\270\260_Lv3.py" new file mode 100644 index 0000000..04d4b50 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\354\247\225\352\262\200\353\213\244\353\246\254\352\261\264\353\204\210\352\270\260_Lv3.py" @@ -0,0 +1,30 @@ +""" +배열에서 최소값을 찾아 모든 원소에서 빼주고 건널 수 있는지 검사하는 과정 반복 -> 시간초과 +최댓값이 정해져 있으므로 이분탐색으로 풀어보자 +""" + +def solution(stones, k): + + left, right = 1, 200000000 + + while left <= right: + mid = (left + right) // 2 + cnt = 0 + for i in range(len(stones)): + if stones[i] - mid <= 0: + cnt += 1 + if cnt >= k: + # 건널 수 있는 사람이 무한대로 가정 + break + else: + cnt = 0 + if cnt >= k: + right = mid - 1 + else: + left = mid + 1 + + answer = left + + return answer + +print(solution([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3)) \ No newline at end of file diff --git "a/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\355\226\211\353\240\254_\355\205\214\353\221\220\353\246\254_\355\232\214\354\240\204\355\225\230\352\270\260_Lv2.py" "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\355\226\211\353\240\254_\355\205\214\353\221\220\353\246\254_\355\232\214\354\240\204\355\225\230\352\270\260_Lv2.py" new file mode 100644 index 0000000..4c2e159 --- /dev/null +++ "b/out/production/algorithm-study/changyeop/\355\224\204\353\241\234\352\267\270\353\236\230\353\250\270\354\212\244_\355\226\211\353\240\254_\355\205\214\353\221\220\353\246\254_\355\232\214\354\240\204\355\225\230\352\270\260_Lv2.py" @@ -0,0 +1,28 @@ +def solution(rows, columns, queries): + answer = [] + mat = [[(j-1) * columns + i for i in range(1, columns+1)] for j in range(1, rows+1)] + # print(mat) + moveX = [0, 1, 0, -1] + moveY = [1, 0, -1, 0] + + for tr, tc, br, bc in queries: + # print(tl, tr, bl, br) + curR, curC = tr-1, tc-1 + temp = mat[curR][curC] + result = temp + for i in range(4): + while (curR + moveY[i]) in range(tr-1, br) and (curC + moveX[i]) in range(tc-1, bc): + nr, nc = curR + moveY[i], curC + moveX[i] + mat[curR][curC] = mat[nr][nc] + result = min(result, mat[curR][curC]) + curR, curC = nr, nc + mat[tr-1][tc] = temp + # print(mat) + answer.append(result) + + return answer + +rows = 6 +columns = 6 +queries = [[2,2,5,4],[3,3,6,6],[5,1,6,3]] +print(solution(rows, columns, queries)) \ No newline at end of file