From ed8f87d5205987f4b906d2ed29d9bee1896f1a37 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 31 Aug 2020 06:36:20 +0900 Subject: [PATCH 001/193] solve baekjoon 1158 --- src/do02reen24/data-structure/baekjoon_1158.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_1158.py diff --git a/src/do02reen24/data-structure/baekjoon_1158.py b/src/do02reen24/data-structure/baekjoon_1158.py new file mode 100644 index 0000000..27fe6fe --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_1158.py @@ -0,0 +1,12 @@ +import sys + +if __name__ == '__main__': + n, k = map(int, sys.stdin.readline().split()) + permutation = list(range(1, n + 1)) + answer = [] + index = 0 + + while len(permutation): + index = (index + k - 1) % len(permutation) + answer.append(permutation.pop(index)) + print("<"+', '.join(map(str, answer))+">") \ No newline at end of file From a7b8fe651ba1cdb49c5befaa4ad23c822ef65fb4 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 1 Sep 2020 21:52:18 +0900 Subject: [PATCH 002/193] solve baekjoon 2346 --- .../data-structure/baekjoon_2346.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_2346.py diff --git a/src/do02reen24/data-structure/baekjoon_2346.py b/src/do02reen24/data-structure/baekjoon_2346.py new file mode 100644 index 0000000..47b1e93 --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_2346.py @@ -0,0 +1,22 @@ +import sys + +if __name__ == '__main__': + n = int(sys.stdin.readline().rstrip()) + inputs = list(map(int, sys.stdin.readline().split())) + position = list(range(1, n+1)) + balloons = [[inputs[i], position[i]] for i in range(0, n)] + + result = [] + index = 0 + while True: + b = balloons.pop(index) + result.append(b[1]) + length = len(balloons) + if length == 0: + break + if b[0] > 0: + index = (index + b[0] - 1) % length + else: + index = (index + b[0] + length) % length + + print(' '.join(map(str,result))) \ No newline at end of file From 66b4d5868998d13b33df25e0b43bbcc4307c463a Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 4 Sep 2020 21:08:08 +0900 Subject: [PATCH 003/193] Doc: Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 백준 1158문제 README.md 추가 --- src/Do-ho/README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/Do-ho/README.md b/src/Do-ho/README.md index e69de29..c4d8b41 100644 --- a/src/Do-ho/README.md +++ b/src/Do-ho/README.md @@ -0,0 +1,51 @@ +# :fire: Week1 + +## :question: 백준 1158번 문제 (요세푸스 순열) +- 처음 풀었던 방식 + ```python + a, b = map(int, input().split()) + + linked_list = [] + queue = [] + count = 1 + idx = 0 + + for i in range(a): + linked_list.append(str(i+1)) + + while(len(linked_list)!=0): + if(count==b): + queue.append(linked_list[idx]) + linked_list.remove(linked_list[idx]) + count = 1 + else: + count += 1 + idx = (idx + 1)%len(linked_list) + + print('<'+', '.join(queue)+'>') + ``` + + - 시간초과.... + - 따라서 카운트를 하나씩 올리는 것이 아닌 바로 올려서 검사해도 된다고 생각했음 + +- 두 번째 풀었던 방식 + + ```python + N, K = map(int, input().split()) + + numArr = [] + queue = [] + idx = 0 + + for i in range(N): + numArr.append(str(i+1)) + + while(len(numArr)!=0): + idx = (idx + (K-1)) % len(numArr) + popData = numArr.pop(idx) + queue.append(popData) + + print('<'+', '.join(queue)+'>') + ``` + + \ No newline at end of file From dc3f279238d951f422b033fcb8500af0dabe2fd7 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 4 Sep 2020 21:09:13 +0900 Subject: [PATCH 004/193] Add: Solve boj_1158 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - list로 구현 --- src/Do-ho/dataStructor/boj_1158.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/Do-ho/dataStructor/boj_1158.py diff --git a/src/Do-ho/dataStructor/boj_1158.py b/src/Do-ho/dataStructor/boj_1158.py new file mode 100644 index 0000000..a76b5c9 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_1158.py @@ -0,0 +1,15 @@ +N, K = map(int, input().split()) + +numArr = [] +queue = [] +idx = 0 + +for i in range(N): + numArr.append(str(i+1)) + +while(len(numArr)!=0): + idx = (idx + (K-1)) % len(numArr) + popData = numArr.pop(idx) + queue.append(popData) + +print('<'+', '.join(queue)+'>') \ No newline at end of file From 527db0359e718cd1890426fe84e96970250c9634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 00:56:45 +0900 Subject: [PATCH 005/193] solve 1158 --- 1158/Main.java | 38 ++++++++++++++++++++++++ 1158/README.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 1158/Main.java create mode 100644 1158/README.md diff --git a/1158/Main.java b/1158/Main.java new file mode 100644 index 0000000..7460e29 --- /dev/null +++ b/1158/Main.java @@ -0,0 +1,38 @@ +package boj1158; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + static int n, k; + static Queue queue = new LinkedList<>(); + static ArrayList res = new ArrayList<>(); + 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()); + k = Integer.parseInt(st.nextToken()); + + for (int i = 1; i <= n; i++) queue.add(i); + + while (!queue.isEmpty()) { + for (int i = 0; i < k - 1; i++) queue.add(queue.poll()); + res.add(queue.poll()); + } + + StringBuilder sb = new StringBuilder(); + sb.append("<"); + for (int i = 0; i < res.size(); i++) { + sb.append(res.get(i)); + if (i != res.size() - 1) sb.append(", "); + else sb.append(">"); + } + System.out.println(sb); + } +} + diff --git a/1158/README.md b/1158/README.md new file mode 100644 index 0000000..32cc67f --- /dev/null +++ b/1158/README.md @@ -0,0 +1,79 @@ +--- +layout: post +title: "백준 1107번 리모컨" +subtitle: "Baekjoon algorithm" +date: 2020-02-26 09:51:12 +author: kwon +categories: algorithm +tags: + - Algorithm +--- +# Problem 1107 + +## 리모컨 + +### 문제 +요세푸스 문제는 다음과 같다. + +1번부터 N번까지 N명의 사람이 원을 이루면서 앉아있고, 양의 정수 K(≤ N)가 주어진다. 이제 순서대로 K번째 사람을 제거한다. 한 사람이 제거되면 남은 사람들로 이루어진 원을 따라 이 과정을 계속해 나간다. 이 과정은 N명의 사람이 모두 제거될 때까지 계속된다. 원에서 사람들이 제거되는 순서를 (N, K)-요세푸스 순열이라고 한다. 예를 들어 (7, 3)-요세푸스 순열은 <3, 6, 2, 7, 5, 1, 4>이다. + +N과 K가 주어지면 (N, K)-요세푸스 순열을 구하는 프로그램을 작성하시오. + +### 입력 +첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000) + +### 출력 +예제와 같이 요세푸스 순열을 출력한다. + +### 문제 링크 + + +### 예제 입력 1 +7 3 + +### 예제 출력 1 +<3, 6, 2, 7, 5, 1, 4> + +### solve +- 큐를 사용하여 n개의 원소를 큐에 넣어준다. +- 원의 형태를 한 번 이동할 때 큐의 맨 앞의 원소를 빼서 맨 뒤에 넣어주는 방식으로 구현한다. +- 큐가 빌 때까지 k번 이동하고 원소 하나를 제거하는 것을 반복하고, 제거되는 원소를 차례로 출력한다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + static int n, k; + static Queue queue = new LinkedList<>(); + static ArrayList res = new ArrayList<>(); + 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()); + k = Integer.parseInt(st.nextToken()); + + for (int i = 1; i <= n; i++) queue.add(i); + + while (!queue.isEmpty()) { + for (int i = 0; i < k - 1; i++) queue.add(queue.poll()); + res.add(queue.poll()); + } + + StringBuilder sb = new StringBuilder(); + sb.append("<"); + for (int i = 0; i < res.size(); i++) { + sb.append(res.get(i)); + if (i != res.size() - 1) sb.append(", "); + else sb.append(">"); + } + System.out.println(sb); + } +} +``` From 141e889d54f14f78481badb3d3b68a46f1f7407c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 00:58:13 +0900 Subject: [PATCH 006/193] move files --- {1158 => src/kyu9341/1158}/Main.java | 0 {1158 => src/kyu9341/1158}/README.md | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {1158 => src/kyu9341/1158}/Main.java (100%) rename {1158 => src/kyu9341/1158}/README.md (100%) diff --git a/1158/Main.java b/src/kyu9341/1158/Main.java similarity index 100% rename from 1158/Main.java rename to src/kyu9341/1158/Main.java diff --git a/1158/README.md b/src/kyu9341/1158/README.md similarity index 100% rename from 1158/README.md rename to src/kyu9341/1158/README.md From efdd763055f2f8edfb06d15b4f0c7f9f2741ae9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 01:16:40 +0900 Subject: [PATCH 007/193] update 1158 README --- src/kyu9341/1158/README.md | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/kyu9341/1158/README.md b/src/kyu9341/1158/README.md index 32cc67f..055424a 100644 --- a/src/kyu9341/1158/README.md +++ b/src/kyu9341/1158/README.md @@ -1,16 +1,6 @@ ---- -layout: post -title: "백준 1107번 리모컨" -subtitle: "Baekjoon algorithm" -date: 2020-02-26 09:51:12 -author: kwon -categories: algorithm -tags: - - Algorithm ---- -# Problem 1107 +# Problem 1158 -## 리모컨 +## 요세푸스 문제 ### 문제 요세푸스 문제는 다음과 같다. From fd472fe0255dfc4819de2d2af3cd437269f78a39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 01:21:13 +0900 Subject: [PATCH 008/193] solve 1406 --- src/kyu9341/1406/Main.java | 35 ++++++++++++++++++ src/kyu9341/1406/README.md | 74 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 src/kyu9341/1406/Main.java create mode 100644 src/kyu9341/1406/README.md diff --git a/src/kyu9341/1406/Main.java b/src/kyu9341/1406/Main.java new file mode 100644 index 0000000..7b583d0 --- /dev/null +++ b/src/kyu9341/1406/Main.java @@ -0,0 +1,35 @@ +package boj1406; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Stack; +import java.util.StringTokenizer; + +public class Main { + static String str; + static int m; + static Stack left = new Stack<>(); + static Stack right = new Stack<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + str = br.readLine(); + for (int i = 0; i < str.length(); i++) left.push(str.charAt(i)); + + m = Integer.parseInt(br.readLine()); + for (int i = 0; i < m; i++) { + String command = br.readLine(); + if (command.charAt(0) == 'L' && !left.isEmpty()) right.push(left.pop()); + else if (command.charAt(0) == 'D' && !right.isEmpty()) left.push(right.pop()); + else if (command.charAt(0) == 'B' && !left.isEmpty()) left.pop(); + else if (command.charAt(0) == 'P') left.push(command.charAt(2)); + } + + while(!left.isEmpty()) right.push(left.pop()); + StringBuilder sb = new StringBuilder(); + while(!right.isEmpty()) sb.append(right.pop()); + System.out.println(sb); + } +} diff --git a/src/kyu9341/1406/README.md b/src/kyu9341/1406/README.md new file mode 100644 index 0000000..7005266 --- /dev/null +++ b/src/kyu9341/1406/README.md @@ -0,0 +1,74 @@ +# Problem 1406 + +## 에디터 + +### 문제 +한 줄로 된 간단한 에디터를 구현하려고 한다. 이 편집기는 영어 소문자만을 기록할 수 있는 편집기로, 최대 600,000글자까지 입력할 수 있다. + +이 편집기에는 '커서'라는 것이 있는데, 커서는 문장의 맨 앞(첫 번째 문자의 왼쪽), 문장의 맨 뒤(마지막 문자의 오른쪽), 또는 문장 중간 임의의 곳(모든 연속된 두 문자 사이)에 위치할 수 있다. 즉 길이가 L인 문자열이 현재 편집기에 입력되어 있으면, 커서가 위치할 수 있는 곳은 L+1가지 경우가 있다. + +이 편집기가 지원하는 명령어는 다음과 같다. + +L 커서를 왼쪽으로 한 칸 옮김 (커서가 문장의 맨 앞이면 무시됨) + +D 커서를 오른쪽으로 한 칸 옮김 (커서가 문장의 맨 뒤이면 무시됨) + +B 커서 왼쪽에 있는 문자를 삭제함 (커서가 문장의 맨 앞이면 무시됨) + +삭제로 인해 커서는 한 칸 왼쪽으로 이동한 것처럼 나타나지만, 실제로 커서의 오른쪽에 있던 문자는 그대로임 + +P $ $라는 문자를 커서 왼쪽에 추가함 + +초기에 편집기에 입력되어 있는 문자열이 주어지고, 그 이후 입력한 명령어가 차례로 주어졌을 때, 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 구하는 프로그램을 작성하시오. 단, 명령어가 수행되기 전에 커서는 문장의 맨 뒤에 위치하고 있다고 한다. + +### 입력 +첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수를 나타내는 정수 M(1 ≤ M ≤ 500,000)이 주어진다. 셋째 줄부터 M개의 줄에 걸쳐 입력할 명령어가 순서대로 주어진다. 명령어는 위의 네 가지 중 하나의 형태로만 주어진다. + +### 출력 +첫째 줄에 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 출력한다. + +### 문제 링크 + + + +### solve +- 스택을 두 개 사용하여 왼쪽의 스택과 오른쪽 스택의 사이를 커서의 위치라고 생각한다. +- 커서를 왼쪽으로 옮기면 왼쪽 스택의 top원소를 오른쪽 스택의 top으로 옮긴다. +- 위와 같은 방식으로 우측 이동, 삽입, 삭제를 구현했다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Stack; +import java.util.StringTokenizer; + +public class Main { + static String str; + static int m; + static Stack left = new Stack<>(); + static Stack right = new Stack<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + str = br.readLine(); + for (int i = 0; i < str.length(); i++) left.push(str.charAt(i)); + + m = Integer.parseInt(br.readLine()); + for (int i = 0; i < m; i++) { + String command = br.readLine(); + if (command.charAt(0) == 'L' && !left.isEmpty()) right.push(left.pop()); + else if (command.charAt(0) == 'D' && !right.isEmpty()) left.push(right.pop()); + else if (command.charAt(0) == 'B' && !left.isEmpty()) left.pop(); + else if (command.charAt(0) == 'P') left.push(command.charAt(2)); + } + + while(!left.isEmpty()) right.push(left.pop()); + StringBuilder sb = new StringBuilder(); + while(!right.isEmpty()) sb.append(right.pop()); + System.out.println(sb); + } +} +``` From 3189cb88491e0cda01eb889e909c36aaca6a08bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 01:32:24 +0900 Subject: [PATCH 009/193] solve 2346 --- src/kyu9341/2346/Main.java | 57 ++++++++++++++++++++++++ src/kyu9341/2346/README.md | 88 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 src/kyu9341/2346/Main.java create mode 100644 src/kyu9341/2346/README.md diff --git a/src/kyu9341/2346/Main.java b/src/kyu9341/2346/Main.java new file mode 100644 index 0000000..68f8033 --- /dev/null +++ b/src/kyu9341/2346/Main.java @@ -0,0 +1,57 @@ +package boj2346; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.StringTokenizer; + +public class Main { + + static Deque dq = new ArrayDeque<>(); + static int n; + static Balloon[] balloon; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + balloon = new Balloon[n]; + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 1; i <= n; i++) { + dq.add(new Balloon(i, Integer.parseInt(st.nextToken()))); + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + Balloon cur = dq.pollFirst(); + sb.append(cur.num); + if (i != n - 1) sb.append(" "); + if (cur.count < 0) moveLeft(-cur.count); + else moveRight(cur.count); + } + System.out.println(sb); + } + + static void moveLeft(int num) { + for (int i = 0; i < num; i++) { + if (!dq.isEmpty()) dq.addFirst(dq.pollLast()); + } + } + + static void moveRight(int num) { // 우측으로 이동하는 경우는 한번 덜 이동 - 터트린 풍선은 개수 count + for (int i = 0; i < num - 1; i++) { + if (!dq.isEmpty()) dq.addLast(dq.pollFirst()); + } + } + + static class Balloon { + int num; + int count; + public Balloon(int num, int count) { + this.num = num; + this.count = count; + } + } + +} diff --git a/src/kyu9341/2346/README.md b/src/kyu9341/2346/README.md new file mode 100644 index 0000000..89cce6f --- /dev/null +++ b/src/kyu9341/2346/README.md @@ -0,0 +1,88 @@ +# Problem 2346 + +## 풍선 터뜨리기 + +### 문제 +N개의 풍선이 있다. 각 풍선 안에는 -N부터 N까지의 수가 적혀있는 종이가 들어 있다. 이 풍선들을 다음과 같은 규칙으로 터뜨린다. + +우선, 제일 처음에는 1번 풍선을 터뜨린다. 다음에는 풍선 안에 있는 종이를 꺼내어 그 종이에 적혀있는 값만큼 이동하여 다음 풍선을 터뜨린다. 양수가 적혀 있을 경우에는 오른쪽으로, 음수가 적혀 있을 때는 왼쪽으로 이동한다. 풍선은 원형으로 놓여 있다고 생각한다. 즉, 1번 풍선의 왼쪽에 N번 풍선이 있고, N번 풍선의 오른쪽에 1번 풍선이 있는 것이다. 이동할 때에는 이미 터진 풍선은 빼고 생각한다. + +예를 들어 다섯 개의 풍선 안에 차례로 3, 2, 1, -3, -1이 적혀 있었다고 하자. 이 경우 3이 적혀 있는 1번 풍선, -3이 적혀 있는 4번 풍선, -1이 적혀 있는 5번 풍선, 1이 적혀 있는 3번 풍선, 2가 적혀 있는 2번 풍선의 순서대로 터지게 된다. + +### 입력 +첫째 줄에 자연수 N(1≤N≤1,000)이 주어진다. 다음 줄에는 차례로 각 풍선 안의 종이에 적혀 있는 수가 주어진다. 편의상 0은 적혀있지 않다고 가정하자. + +### 출력 +첫째 줄에 터진 풍선의 번호를 차례로 나열한다. + +### 문제 링크 + + + +### solve +- 풍선이 원형으로 놓여 있고, 풍선의 번호에 따라 좌, 우로 이동하기 때문에 덱을 사용했다. +- balloon 클래스를 만들어 풍선의 번호와 적힌 숫자를 담는다. +- 좌측으로 이동하는 경우 - 덱의 맨 뒤 원소를 맨 앞으로 이동 +- 우측이로 이동하는 경우 - 덱의 맨 앞 원소를 맨 뒤로 이동 + - 이 때, 현재 풍선을 터트린 뒤 이동하기 때문에 우측으로 이동하는 경우는 한 번 덜 이동한다. +- 풍선을 터뜨릴 때마다 해당 풍선의 번호를 기록한다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.StringTokenizer; + +public class Main { + + static Deque dq = new ArrayDeque<>(); + static int n; + static Balloon[] balloon; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + balloon = new Balloon[n]; + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 1; i <= n; i++) { + dq.add(new Balloon(i, Integer.parseInt(st.nextToken()))); + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + Balloon cur = dq.pollFirst(); + sb.append(cur.num); + if (i != n - 1) sb.append(" "); + if (cur.count < 0) moveLeft(-cur.count); + else moveRight(cur.count); + } + System.out.println(sb); + } + + static void moveLeft(int num) { + for (int i = 0; i < num; i++) { + if (!dq.isEmpty()) dq.addFirst(dq.pollLast()); + } + } + + static void moveRight(int num) { // 우측으로 이동하는 경우는 한번 덜 이동 - 터트린 풍선은 개수 count + for (int i = 0; i < num - 1; i++) { + if (!dq.isEmpty()) dq.addLast(dq.pollFirst()); + } + } + + static class Balloon { + int num; + int count; + public Balloon(int num, int count) { + this.num = num; + this.count = count; + } + } + +} + +``` From 803f3c0f3abd535444945abffc96dca842ee8ab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 5 Sep 2020 02:06:35 +0900 Subject: [PATCH 010/193] solve 2957 --- src/kyu9341/2957/Main.java | 45 ++++++++++++++++++++++++++++ src/kyu9341/2957/README.md | 60 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 src/kyu9341/2957/Main.java create mode 100644 src/kyu9341/2957/README.md diff --git a/src/kyu9341/2957/Main.java b/src/kyu9341/2957/Main.java new file mode 100644 index 0000000..f586a3f --- /dev/null +++ b/src/kyu9341/2957/Main.java @@ -0,0 +1,45 @@ +package boj2957; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Main { + static int n; + static int c = 0; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + Node root = new Node(Integer.parseInt(br.readLine())); + for (int i = 0; i < n - 1; i++) { + int x = Integer.parseInt(br.readLine()); + insert(x, root); + System.out.println(c); + } + } + + static void insert(int x, Node node) { + c++; + if (x < node.data) { + if (node.left == null) node.left = new Node(x); + else insert(x, node.left); + } + else { + if (node.right == null) node.right = new Node(x); + else insert(x, node.right); + } + } + + static class Node { + int data; + Node left; + Node right; + + public Node(int data) { + this.data = data; + this.left = null; + this.right = null; + } + } +} diff --git a/src/kyu9341/2957/README.md b/src/kyu9341/2957/README.md new file mode 100644 index 0000000..93c62f5 --- /dev/null +++ b/src/kyu9341/2957/README.md @@ -0,0 +1,60 @@ +# Problem 2957 + +## 이진 탐색 트리 + +### 문제 링크 + + + +### solve +- 단순히 노드 클래스를 만들고 문제에서 주어진 대로 삽입 연산을 구현하니까 시간초과가 난다. +- 졸리니까 일단 잔다..ㅜ + + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Main { + static int n; + static int c = 0; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + Node root = new Node(Integer.parseInt(br.readLine())); + for (int i = 0; i < n - 1; i++) { + int x = Integer.parseInt(br.readLine()); + insert(x, root); + System.out.println(c); + } + } + + static void insert(int x, Node node) { + c++; + if (x < node.data) { + if (node.left == null) node.left = new Node(x); + else insert(x, node.left); + } + else { + if (node.right == null) node.right = new Node(x); + else insert(x, node.right); + } + } + + static class Node { + int data; + Node left; + Node right; + + public Node(int data) { + this.data = data; + this.left = null; + this.right = null; + } + } +} + +``` From 945d21d1d4e6f0afab85b76fabe5b1cc7a1d0d65 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 03:46:16 +0900 Subject: [PATCH 011/193] Doc: Update README.md --- src/Do-ho/README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Do-ho/README.md b/src/Do-ho/README.md index c4d8b41..a409323 100644 --- a/src/Do-ho/README.md +++ b/src/Do-ho/README.md @@ -48,4 +48,10 @@ print('<'+', '.join(queue)+'>') ``` - \ No newline at end of file + + +## :question: 백준 1406번 문제 (에디터) + +- 커맨드에 따라서 함수를 나눠 구현해야 할 것 같다. +- 복잡도에 대한 부분을 개선하면 런타임 에러가 발생하지 않지 않을까... +- 아니면 hidden case가 있을까...? \ No newline at end of file From 3b2851782604c9b0e8a779601d61b167793e33e7 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 03:46:40 +0900 Subject: [PATCH 012/193] Add: Solve boj_1406 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 런타임 에러 발생 --- src/Do-ho/dataStructor/boj_1406.py | 58 ++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/Do-ho/dataStructor/boj_1406.py diff --git a/src/Do-ho/dataStructor/boj_1406.py b/src/Do-ho/dataStructor/boj_1406.py new file mode 100644 index 0000000..014ce08 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_1406.py @@ -0,0 +1,58 @@ +initString = input() +M = int(input()) +cursor = len(initString) + +def process(command): + global initString + if len(command)==1: + singleCommand(command[0]) + else: + commandP(command[1]) + +def singleCommand(command): + if command == 'L' : + commandL() + elif command == 'D': + commandD() + elif command == 'B': + commandB() + +def commandP(ch): + global initString, cursor, M + if cursor == len(initString): + initString = initString + ch + else: + initString = initString[:cursor] + ch + initString[cursor:] + M += 1 + cursor += 1 + +def commandL(): + global cursor + if cursor==0: + return + cursor -= 1 + +def commandD(): + global cursor + if cursor==0: + return + cursor += 1 + +def commandB(): + global cursor, initString + if cursor==0: + return + elif cursor==len(initString): + initString = initString[:cursor-1] + cursor -= 1 + else: + initString = initString[:cursor-1] + initString[cursor:] + cursor -= 1 + +for i in range(M): + inputString = input() + command = inputString.split(' ') + process(command) + +print(initString) + From 795d5fe794c34d06fd17c9f448cefacab142f1f0 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 04:16:43 +0900 Subject: [PATCH 013/193] Add: Solve boj_2346 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 앞에서 푼 1158문제와 비슷한 문제라고 생각이 들었음. - 로직이 비슷하다고 생각 --- src/Do-ho/dataStructor/boj_2346.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/Do-ho/dataStructor/boj_2346.py diff --git a/src/Do-ho/dataStructor/boj_2346.py b/src/Do-ho/dataStructor/boj_2346.py new file mode 100644 index 0000000..c4e778a --- /dev/null +++ b/src/Do-ho/dataStructor/boj_2346.py @@ -0,0 +1,24 @@ +N = int(input()) + +inputString = input().split(' ') +numArr = [] +queue = [] +idx = 0 + +for i in range(N): + numArr.append(str(i+1)) + +queue.append(numArr.pop(0)) +inputString.pop(0) +idx = ((idx + int(inputString[idx])) + len(numArr)) % len(numArr) +print(idx) +while(len(numArr)!=0): + popData = numArr.pop(idx) + idx = ((idx + (int(inputString[idx])-1)) + len(numArr)) % len(numArr) + inputString.pop(idx) + queue.append(popData) + +print('<'+', '.join(queue)+'>') + + +# 움직이는거 queue로 하면 될 듯했는데.. 졸려서 잤어요... \ No newline at end of file From 0302de3028971f944d400ea84f2e9f9935ca5465 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 12:29:14 +0900 Subject: [PATCH 014/193] Doc: 200905 minutes of meeting --- mom/mom20200905.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 mom/mom20200905.md diff --git a/mom/mom20200905.md b/mom/mom20200905.md new file mode 100644 index 0000000..ca4e8ee --- /dev/null +++ b/mom/mom20200905.md @@ -0,0 +1,23 @@ +# :family_man_man_girl_boy: 회의록 + +### :question: 개인의 생활에 있어서 미션에 힘듦이 있었나. + +- 미션에 열중하느라 알고리즘에 대해 공부할 시간이 없긴 했으나 쉬운 3 문제, 어려운 1 문제 유지하는 것은 좋은 것 같다. + +- 향후 계속적인 조율의 시간을 가지는 것이 좋을 것 같다. + + + +### :hammer: 향후 피어 세션 계획 + +- **10:00 ~ 10:15** 스터디에 대한 이야기 + +- **10:15 ~ 11:50** 코드 분석 및 알고리즘 공유 + +- **11:50 ~ 12:00** 다음 주제 선정 및 문제 공유 + + + +### :bell: 기타 + +- 2957번 문제와 같은 경우 다음 주까지 다시 풀어오기 \ No newline at end of file From bbf0110326a516419b901074f2c41eb53419ad49 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 12:36:09 +0900 Subject: [PATCH 015/193] Doc: update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 43a49a8..823c0a1 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,9 @@ ## :green_book: Week Study -| | 1 | 2 | 3 | 4 | -| ----- | :--: | :--: | :--: | :--: | -| 1주차 | | | | | +| | 1 | 2 | 3 | 4 | +| ----- | :---------------------------------------------------: | :--------------------------------------------: | :---------------------------------------------------: | :----------------------------------------------------: | +| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | ## :blue_book: Additional Study From c178b2c57cfaf02e83df5e32125becfa9598a25b Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 5 Sep 2020 12:37:11 +0900 Subject: [PATCH 016/193] Doc: post 200912 problems - rename contents/README.md --- contents/200905.md | 2 +- contents/README.md.md | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 contents/README.md.md diff --git a/contents/200905.md b/contents/200905.md index ec73445..d29072b 100644 --- a/contents/200905.md +++ b/contents/200905.md @@ -1,4 +1,4 @@ -# :fire: 금주의 문제 +# :fire: 금주의 문제 (200905) > 이번 주 주제는 자료구조입니다. diff --git a/contents/README.md.md b/contents/README.md.md new file mode 100644 index 0000000..9262241 --- /dev/null +++ b/contents/README.md.md @@ -0,0 +1,11 @@ +# :fire: 금주의 문제 (200912) + +> 이번 주 주제는 자료구조 2탄입니다. + +https://www.acmicpc.net/problem/11286 + +https://programmers.co.kr/learn/courses/30/lessons/42578 + +https://www.acmicpc.net/problem/1991 + +https://www.acmicpc.net/problem/2957 \ No newline at end of file From 860872b44ad21345661145f72a0cc4ff3c515782 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Sat, 5 Sep 2020 12:39:46 +0900 Subject: [PATCH 017/193] Rename README.md.md to README.md --- contents/{README.md.md => README.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename contents/{README.md.md => README.md} (85%) diff --git a/contents/README.md.md b/contents/README.md similarity index 85% rename from contents/README.md.md rename to contents/README.md index 9262241..8d294c7 100644 --- a/contents/README.md.md +++ b/contents/README.md @@ -8,4 +8,4 @@ https://programmers.co.kr/learn/courses/30/lessons/42578 https://www.acmicpc.net/problem/1991 -https://www.acmicpc.net/problem/2957 \ No newline at end of file +https://www.acmicpc.net/problem/2957 From b322da2d9553e44d95a9c74ed843f2d49c48007e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 6 Sep 2020 01:14:40 +0900 Subject: [PATCH 018/193] solve 11286 --- src/kyu9341/11286/Main.java | 34 ++++++++++++++++++++++++++ src/kyu9341/11286/README.md | 48 +++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/kyu9341/11286/Main.java create mode 100644 src/kyu9341/11286/README.md diff --git a/src/kyu9341/11286/Main.java b/src/kyu9341/11286/Main.java new file mode 100644 index 0000000..188c6d9 --- /dev/null +++ b/src/kyu9341/11286/Main.java @@ -0,0 +1,34 @@ +package boj11286; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Comparator; +import java.util.PriorityQueue; + +public class Main { + + static int n; + static PriorityQueue pq = new PriorityQueue<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + if (Math.abs(o1) == Math.abs(o2)) return o1 > o2 ? 1 : -1; + return Math.abs(o1) > Math.abs(o2) ? 1 : -1; + } + }); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + int x = Integer.parseInt(br.readLine()); + if (x == 0) { + if (pq.isEmpty()) sb.append("0" + '\n'); + else sb.append(pq.poll().toString() + '\n'); + } + else pq.add(x); + } + System.out.println(sb); + } +} diff --git a/src/kyu9341/11286/README.md b/src/kyu9341/11286/README.md new file mode 100644 index 0000000..6b25b91 --- /dev/null +++ b/src/kyu9341/11286/README.md @@ -0,0 +1,48 @@ +# Problem 11286 + +## 절대값 힙 + +### 문제 링크 + + + +### solve + +- 우선순위 큐를 활용하여 절대값이 작은 수에 가장 높은 우선순위를 주어 구현했다. + - 이 때, 절대값이 같은 경우 더 작은 수가 우선이 되는 것을 고려한다. + +### 코드 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Comparator; +import java.util.PriorityQueue; + +public class Main { + + static int n; + static PriorityQueue pq = new PriorityQueue<>(new Comparator() { + @Override + public int compare(Integer o1, Integer o2) { + if (Math.abs(o1) == Math.abs(o2)) return o1 > o2 ? 1 : -1; + return Math.abs(o1) > Math.abs(o2) ? 1 : -1; + } + }); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + int x = Integer.parseInt(br.readLine()); + if (x == 0) { + if (pq.isEmpty()) sb.append("0" + '\n'); + else sb.append(pq.poll().toString() + '\n'); + } + else pq.add(x); + } + System.out.println(sb); + } +} +``` From 5c917cfbc7bfeef5fc33fd1af1c5480f05802b56 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 6 Sep 2020 15:38:27 +0900 Subject: [PATCH 019/193] =?UTF-8?q?solve=20baekjoon=201406=20=EC=B2=AB?= =?UTF-8?q?=EB=B2=88=EC=A7=B8=20=EC=A0=9C=EC=B6=9C:=20=EB=9F=B0=ED=83=80?= =?UTF-8?q?=EC=9E=84=20=EC=97=90=EB=9F=AC=20=EB=91=90=EB=B2=88=EC=A7=B8=20?= =?UTF-8?q?=EC=A0=9C=EC=B6=9C:=20=EC=84=B1=EA=B3=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../data-structure/baekjoon_1406.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_1406.py diff --git a/src/do02reen24/data-structure/baekjoon_1406.py b/src/do02reen24/data-structure/baekjoon_1406.py new file mode 100644 index 0000000..9f40d66 --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_1406.py @@ -0,0 +1,19 @@ +import sys + +if __name__ == '__main__': + stackLeft = list(sys.stdin.readline().rstrip()) + stackRight = list() + + n = int(sys.stdin.readline().rstrip()) + for i in range(0, n): + command = list(sys.stdin.readline().split()) + if command[0] == 'L' and stackLeft: + stackRight.append(stackLeft.pop()) + elif command[0] == 'D' and stackRight: + stackLeft.append(stackRight.pop()) + elif command[0] == 'B' and stackLeft: + stackLeft.pop() + elif command[0] == 'P': + stackLeft.append(command[1]) + + print(''.join(stackLeft) + ''.join(list(reversed(stackRight)))) \ No newline at end of file From a21c172b6984778048c84f80fcaac82521ae3e6b Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 6 Sep 2020 18:40:43 +0900 Subject: [PATCH 020/193] doc : week1 review --- src/do02reen24/Review/week1.md | 130 +++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 src/do02reen24/Review/week1.md diff --git a/src/do02reen24/Review/week1.md b/src/do02reen24/Review/week1.md new file mode 100644 index 0000000..bf456d5 --- /dev/null +++ b/src/do02reen24/Review/week1.md @@ -0,0 +1,130 @@ +# :fire: week1 + +## :ballot_box_with_check: 백준 1158 + +파이썬으로 알고리즘을 (거의 처음)준비하면서 입력을 받는 것부터 찾아보았다. `input()` 이라는 기능이 있긴 하지만 `sys.stdin.readline()` 을 쓰는 것이 좋다고 한다. + +## :ballot_box_with_check: 백준 1406 + +런타임 에러 → 해결 + +#### 런타임 오류가 발생했던 코드 + +```python +import sys + +if __name__ == '__main__': + string = list(sys.stdin.readline().rstrip()) + cursor = len(string) + + n = int(sys.stdin.readline().rstrip()) + for i in range(0, n): + command = list(sys.stdin.readline().split()) + if command[0] == 'L' and cursor != 0: + cursor -= 1 + elif command[0] == 'D' and cursor != len(string): + cursor += 1 + elif command[0] == 'B' and cursor != 0: + string.pop(cursor - 1) + elif command[0] == 'P': + string.insert(cursor, command[1]) + cursor += 1 + + print(''.join(string)) +``` + +처음엔 돌아만 가면 된다고 생각해서 효율을 고려하지 못한 것 같다. 아래 링크에서 힌트를 얻어 문제를 해결할 수 있었다. + +[https://www.acmicpc.net/board/view/54572](https://www.acmicpc.net/board/view/54572) + +`linked list`를 만들어 해결하려햇으나 코드가 너무 복잡하고 길어지는 것 같아, `stack `2개를 활용하여 문제를 해결할 수 있었다. + +## :ballot_box_with_check: 백준 2346 + +1158번과 비슷하여 쉽게 풀었다. + +## :ballot_box_with_check: 백준 2957 + +런타임 에러 → 시간초과 → 메모리 초과 + +### 런타임 에러 + +```python +import sys + +class Node(object): + def __init__(self, n): + self.n = n + self.left = None + self.right = None + +class BinarySearchTree(object): + def __init__(self): + self.root = None + self.count = 0 + + def insert(self, n, node): + if self.root == None: + self.root = Node(n) + else: + self.count += 1 + if node.n < n: + if node.left == None: + newNode = Node(n) + node.left = newNode + else: + self.insert(n, node.left) + else: + if node.right == None: + newNode = Node(n) + node.right = newNode + else: + self.insert(n, node.right) + return self.root, self.count + +if __name__ == '__main__': + N = int(sys.stdin.readline().rstrip()) + bst = BinarySearchTree() + node = None + + for i in range(0, N): + n = int(sys.stdin.readline().rstrip()) + node, count = bst.insert(n, node) + print(count) +``` + +파이썬은 재귀 호출에 한계가 있다고 한다. 따라서 재귀 호출이 많이 된다면 이를 늘려줄 필요가 있다. + +```python +import sys +sys.setrecursionlimit(300000) +``` + +위 코드를 추가하여 런타임 에러를 해결 할 수 있었다. + +### 시간 초과 + +런타임 에러를 해결했더니 시간 초과가 발생했다. `python`의 컴파일이 오래걸리기 때문인 경우가 많다고 한다. `pypy3`를 쓰면 빠르게 컴파일 된다고 하여 `pypy3`로 다시 제출해봤다. + +### 메모리 초과 + +`pypy3`로 제출하니까 메모리 초과가 발생했다. 알고리즘 자체에 문제가 있다고 판단해서 코드를 고치기로 했다. 문제의 설명을 그대로 구현하면 `O(n^2)`이라고 한다. + + + +## :pencil2: 고찰 + +### 잘했던 것, 좋았던 것, 도전 해볼 점, 계속할 것 + +* 블로그에 찾아봤던 내용을 정리하는 것은 잘한 것 같다. 다 기억할 수 없기 때문에 정리해놓고 찾아보면 좋을 것 같다. 앞으로도 계속 쓸 계획이다. +* 하루에 문제를 몰아서 풀지 않고 나눠서 풀었다. (물론 해결을 못한 것도 있지만...) + +### 잘못했던 것, 아쉬운 것, 부족한 것, 개선방향 + +* 언어의 동작 원리를 꼼꼼하게 알아보고 사용할 필요가 있는 것 같다. 이전까지는 c++을 사용해서 알고리즘을 풀었었는데 python에서는 동작원리가 달라 논리가 비슷함에도 불구하고 에러가 발생하는 경우가 있었다. +* python으로 입력받는 부분이 낯설어 보고 따라치고 있는데 외우기 위한 노력을 해야 할 것 같다. +* 전 날 친구들과 약속에서 너무 신나게 노는 바람에 늦게 일어나 참여를 못했다. 첫 날의 실수를 만회하기 위해서라도 앞으로는 더욱 열심히 참여해야겠다. + +### 기타 + +* python이 논리를 바로바로 생각하기 쉬워서 좋긴 하나 아직은 c++이 더 익숙한 것 같다. python으로 좀 더 진행해보고 어떤 언어로 코딩테스트를 준비할지 결정해야겠다. \ No newline at end of file From b8d3328a0692253c5979b3a1bcbcfd5e13203c84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 6 Sep 2020 19:39:29 +0900 Subject: [PATCH 021/193] solve 1991 --- src/kyu9341/1991/Main.java | 60 +++++++++++++++++++++++++++++++ src/kyu9341/1991/README.md | 73 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 src/kyu9341/1991/Main.java create mode 100644 src/kyu9341/1991/README.md diff --git a/src/kyu9341/1991/Main.java b/src/kyu9341/1991/Main.java new file mode 100644 index 0000000..357b98b --- /dev/null +++ b/src/kyu9341/1991/Main.java @@ -0,0 +1,60 @@ +package boj1991; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + static int n; + static Node[] tree = new Node[26]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + n = Integer.parseInt(br.readLine()); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + char root = st.nextToken().charAt(0); + char left = st.nextToken().charAt(0); + char right = st.nextToken().charAt(0); + tree[root - 'A'] = new Node(left == '.' ? -1 : left, right == '.' ? -1 : right); + } + preorder('A'); + System.out.println(); + inorder('A'); + System.out.println(); + postorder('A'); + + } + static void preorder(int root) { + if (root == -1) return; + System.out.print((char)root); + preorder(tree[root - 'A'].left); + preorder(tree[root - 'A'].right); + } + + static void inorder(int root) { + if (root == -1) return; + inorder(tree[root - 'A'].left); + System.out.print((char)root); + inorder(tree[root - 'A'].right); + } + + static void postorder(int root) { + if (root == -1) return; + postorder(tree[root - 'A'].left); + postorder(tree[root - 'A'].right); + System.out.print((char)root); + } + + static class Node { + int left; + int right; + Node (int left, int right){ + this.left = left; + this.right = right; + } + } +} diff --git a/src/kyu9341/1991/README.md b/src/kyu9341/1991/README.md new file mode 100644 index 0000000..2a5d7b1 --- /dev/null +++ b/src/kyu9341/1991/README.md @@ -0,0 +1,73 @@ +# Problem 1991 + +## 트리 순회 + +### 문제 링크 + + + +### solve +- 항상 A부터 차례로 입력되고 최대 26개이기 때문에 26개의 Node배열을 만들어 0 : A, 1 : B ... 로 대응시켜 사용하였다. +- 자식 노드가 없는 경우 -1, 있는 경우면 해당 문자의 아스키 코드 값을 저장하고, dfs로 각각 전위 순회, 중위 순회, 후위 순회를 구현했다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + static int n; + static Node[] tree = new Node[26]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + n = Integer.parseInt(br.readLine()); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + char root = st.nextToken().charAt(0); + char left = st.nextToken().charAt(0); + char right = st.nextToken().charAt(0); + tree[root - 'A'] = new Node(left == '.' ? -1 : left, right == '.' ? -1 : right); + } + preorder('A'); + System.out.println(); + inorder('A'); + System.out.println(); + postorder('A'); + + } + static void preorder(int root) { + if (root == -1) return; + System.out.print((char)root); + preorder(tree[root - 'A'].left); + preorder(tree[root - 'A'].right); + } + + static void inorder(int root) { + if (root == -1) return; + inorder(tree[root - 'A'].left); + System.out.print((char)root); + inorder(tree[root - 'A'].right); + } + + static void postorder(int root) { + if (root == -1) return; + postorder(tree[root - 'A'].left); + postorder(tree[root - 'A'].right); + System.out.print((char)root); + } + + static class Node { + int left; + int right; + Node (int left, int right){ + this.left = left; + this.right = right; + } + } +} +``` From 5b57a727efba88609374d82cad650472fba65f6e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 10 Sep 2020 23:48:45 +0900 Subject: [PATCH 022/193] solve programmers 42578 --- src/do02reen24/data-structure/programmers_42578.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/do02reen24/data-structure/programmers_42578.py diff --git a/src/do02reen24/data-structure/programmers_42578.py b/src/do02reen24/data-structure/programmers_42578.py new file mode 100644 index 0000000..5d92e08 --- /dev/null +++ b/src/do02reen24/data-structure/programmers_42578.py @@ -0,0 +1,13 @@ +def solution(clothes): + answer = 1 + clothesMap = dict() + for c in clothes: + if clothesMap.get(c[1]) == None: + clothesMap[c[1]] = [] + clothesMap[c[1]].append(c[0]) + + for value in clothesMap.values(): + answer *= (len(value) + 1) + + answer -= 1 + return answer \ No newline at end of file From e5437ae24a2e4704cac1ad9685b1da072d6a90b9 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 11 Sep 2020 00:53:33 +0900 Subject: [PATCH 023/193] solve baekjoon 1991 --- .../data-structure/baekjoon_1991.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_1991.py diff --git a/src/do02reen24/data-structure/baekjoon_1991.py b/src/do02reen24/data-structure/baekjoon_1991.py new file mode 100644 index 0000000..48f28ff --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_1991.py @@ -0,0 +1,59 @@ +import sys + +class Node(object): + def __init__(self, depth, left, right): + self.depth = depth + self.left = left + self.right = right + +def preOrder(tree, index): + if index != '.': + node = tree[index] + print(index, end='') + preOrder(tree, node.left) + preOrder(tree, node.right) + return + +def inOrder(tree, index): + if index != '.': + node = tree[index] + inOrder(tree, node.left) + print(index, end='') + inOrder(tree, node.right) + return + +def postOrder(tree, index): + if index != '.': + node = tree[index] + postOrder(tree, node.left) + postOrder(tree, node.right) + print(index, end='') + return + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + tree = None + treeRoot = None + + for i in range(n): + root, left, right = sys.stdin.readline().split() + depth = 0 + if tree == None: + tree = dict() + treeRoot = root + tree[root] = Node(depth, left, right) + else: + tree[root].left = left + tree[root].right = right + depth = tree[root].depth + + if not left=='.': + tree[left] = Node(depth+1, '.', '.') + if not right=='.': + tree[right] = Node(depth+1, '.', '.') + + preOrder(tree, treeRoot) + print() + inOrder(tree, treeRoot) + print() + postOrder(tree, treeRoot) \ No newline at end of file From 179e76b0147bdc68c32dc996e88ae002d1fcb563 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 11 Sep 2020 02:22:06 +0900 Subject: [PATCH 024/193] Doc: rename README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 주차 변경에 따른 문서 수정 --- src/Do-ho/README.md | 58 ++------------------------------------------- src/Do-ho/week1.md | 57 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 56 deletions(-) create mode 100644 src/Do-ho/week1.md diff --git a/src/Do-ho/README.md b/src/Do-ho/README.md index a409323..9b6702d 100644 --- a/src/Do-ho/README.md +++ b/src/Do-ho/README.md @@ -1,57 +1,3 @@ -# :fire: Week1 +# :fire: Week2 -## :question: 백준 1158번 문제 (요세푸스 순열) -- 처음 풀었던 방식 - ```python - a, b = map(int, input().split()) - - linked_list = [] - queue = [] - count = 1 - idx = 0 - - for i in range(a): - linked_list.append(str(i+1)) - - while(len(linked_list)!=0): - if(count==b): - queue.append(linked_list[idx]) - linked_list.remove(linked_list[idx]) - count = 1 - else: - count += 1 - idx = (idx + 1)%len(linked_list) - - print('<'+', '.join(queue)+'>') - ``` - - - 시간초과.... - - 따라서 카운트를 하나씩 올리는 것이 아닌 바로 올려서 검사해도 된다고 생각했음 - -- 두 번째 풀었던 방식 - - ```python - N, K = map(int, input().split()) - - numArr = [] - queue = [] - idx = 0 - - for i in range(N): - numArr.append(str(i+1)) - - while(len(numArr)!=0): - idx = (idx + (K-1)) % len(numArr) - popData = numArr.pop(idx) - queue.append(popData) - - print('<'+', '.join(queue)+'>') - ``` - - - -## :question: 백준 1406번 문제 (에디터) - -- 커맨드에 따라서 함수를 나눠 구현해야 할 것 같다. -- 복잡도에 대한 부분을 개선하면 런타임 에러가 발생하지 않지 않을까... -- 아니면 hidden case가 있을까...? \ No newline at end of file +[[절대값 힙](./dataStructor/boj_11286/README.md)] \ No newline at end of file diff --git a/src/Do-ho/week1.md b/src/Do-ho/week1.md new file mode 100644 index 0000000..a409323 --- /dev/null +++ b/src/Do-ho/week1.md @@ -0,0 +1,57 @@ +# :fire: Week1 + +## :question: 백준 1158번 문제 (요세푸스 순열) +- 처음 풀었던 방식 + ```python + a, b = map(int, input().split()) + + linked_list = [] + queue = [] + count = 1 + idx = 0 + + for i in range(a): + linked_list.append(str(i+1)) + + while(len(linked_list)!=0): + if(count==b): + queue.append(linked_list[idx]) + linked_list.remove(linked_list[idx]) + count = 1 + else: + count += 1 + idx = (idx + 1)%len(linked_list) + + print('<'+', '.join(queue)+'>') + ``` + + - 시간초과.... + - 따라서 카운트를 하나씩 올리는 것이 아닌 바로 올려서 검사해도 된다고 생각했음 + +- 두 번째 풀었던 방식 + + ```python + N, K = map(int, input().split()) + + numArr = [] + queue = [] + idx = 0 + + for i in range(N): + numArr.append(str(i+1)) + + while(len(numArr)!=0): + idx = (idx + (K-1)) % len(numArr) + popData = numArr.pop(idx) + queue.append(popData) + + print('<'+', '.join(queue)+'>') + ``` + + + +## :question: 백준 1406번 문제 (에디터) + +- 커맨드에 따라서 함수를 나눠 구현해야 할 것 같다. +- 복잡도에 대한 부분을 개선하면 런타임 에러가 발생하지 않지 않을까... +- 아니면 hidden case가 있을까...? \ No newline at end of file From 2ad16ab2b865ad7ae55753bc83b02c191bc42da9 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 11 Sep 2020 02:23:03 +0900 Subject: [PATCH 025/193] Add: solve boj 11286 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 우선순위 큐를 이용한 문제 해결 - 튜플을 이용함 - 입력 방식의 차이에 따른 속도 생각 --- src/Do-ho/dataStructor/boj_11286/README.md | 60 ++++++++++++ .../dataStructor/boj_11286/boj.11286_3.py | 12 +++ src/Do-ho/dataStructor/boj_11286/boj_11286.py | 92 +++++++++++++++++++ .../dataStructor/boj_11286/boj_11286_2.py | 13 +++ 4 files changed, 177 insertions(+) create mode 100644 src/Do-ho/dataStructor/boj_11286/README.md create mode 100644 src/Do-ho/dataStructor/boj_11286/boj.11286_3.py create mode 100644 src/Do-ho/dataStructor/boj_11286/boj_11286.py create mode 100644 src/Do-ho/dataStructor/boj_11286/boj_11286_2.py diff --git a/src/Do-ho/dataStructor/boj_11286/README.md b/src/Do-ho/dataStructor/boj_11286/README.md new file mode 100644 index 0000000..6f810f4 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_11286/README.md @@ -0,0 +1,60 @@ + + +## 우선 순위 큐 + +1. PriorityQueue를 이용한 방법 + + ```python + import sys + from queue import PriorityQueue + + que = PriorityQueue() + + N = int(sys.stdin.readline()) + + for i in range(N): + x = int(sys.stdin.readline()) + if(x!=0): que.put((abs(x), x)) + else: + if que.empty(): print(0) + else: print(que.get()[1]) + ``` + +2. heapq를 이용한 방법 + + ```python + import sys + import heapq + + N = int(input()) + heap = [] + + for i in range(N): + x = int(sys.stdin.readline()) + if(x!=0): heapq.heappush(heap, (abs(x), x)) + else: + if len(heap)==0: print(0) + else: print(heapq.heappop(heap)[1]) + ``` + + + +## 알게된 점 + +- input()과 sys.stdin.readline의 속도 차이 [참조](https://www.acmicpc.net/blog/view/56) + + - N(=10,000,000), 자연수(10,000 이하)가 적힌 파일을 입력받는데 걸리는 시간을 측정 + + - input()은 12.4443초 + + - int(sys.stdin.readline())은 4.4394초 + + - 제일 빠른건 map(int,os.read(0, 100000000).decode('utf-8').split('\n')) + + - 하지만 0.03초 차이밖에 나지 않음 + + + +## 참조 + +[참조](https://www.youtube.com/watch?v=jfwjyJvbbBI) \ No newline at end of file diff --git a/src/Do-ho/dataStructor/boj_11286/boj.11286_3.py b/src/Do-ho/dataStructor/boj_11286/boj.11286_3.py new file mode 100644 index 0000000..087d765 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_11286/boj.11286_3.py @@ -0,0 +1,12 @@ +import sys +import heapq + +N = int(input()) +heap = [] + +for i in range(N): + x = int(sys.stdin.readline()) + if(x!=0): heapq.heappush(heap, (abs(x), x)) + else: + if len(heap)==0: print(0) + else: print(heapq.heappop(heap)[1]) \ No newline at end of file diff --git a/src/Do-ho/dataStructor/boj_11286/boj_11286.py b/src/Do-ho/dataStructor/boj_11286/boj_11286.py new file mode 100644 index 0000000..5a57b35 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_11286/boj_11286.py @@ -0,0 +1,92 @@ +import math +import sys + +heap = [] + +def swap(parentIdx, childIdx): + global heap + tmp = heap[parentIdx] + heap[parentIdx] = heap[childIdx] + heap[childIdx] = tmp + +def reheapdown(): + global heap + parentIdx = 0 + + leftChildIdx = 1 + rightChildIdx = 2 + while True: + if parentIdx == 0 and leftChildIdx < len(heap) and rightChildIdx < len(heap): + if abs(heap[leftChildIdx]) <= abs(heap[rightChildIdx]): + if leftChildIdx < len(heap) and abs(heap[leftChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[leftChildIdx]) == abs(heap[parentIdx]) and heap[leftChildIdx] >= heap[parentIdx]: return + swap(parentIdx, leftChildIdx) + parentIdx = leftChildIdx + elif rightChildIdx < len(heap) and abs(heap[rightChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[rightChildIdx]) == abs(heap[parentIdx]) and heap[rightChildIdx] >= heap[parentIdx]: return + swap(parentIdx, rightChildIdx) + parentIdx = rightChildIdx + else: + break + else: + if rightChildIdx < len(heap) and abs(heap[rightChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[rightChildIdx]) == abs(heap[parentIdx]) and heap[rightChildIdx] >= heap[parentIdx]: return + swap(parentIdx, rightChildIdx) + parentIdx = rightChildIdx + + elif leftChildIdx < len(heap) and abs(heap[leftChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[leftChildIdx]) == abs(heap[parentIdx]) and heap[leftChildIdx] >= heap[parentIdx]: return + swap(parentIdx, leftChildIdx) + parentIdx = leftChildIdx + else: + break + else: + if leftChildIdx < len(heap) and abs(heap[leftChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[leftChildIdx]) == abs(heap[parentIdx]) and heap[leftChildIdx] >= heap[parentIdx]: return + swap(parentIdx, leftChildIdx) + parentIdx = leftChildIdx + elif rightChildIdx < len(heap) and abs(heap[rightChildIdx]) <= abs(heap[parentIdx]): + if abs(heap[rightChildIdx]) == abs(heap[parentIdx]) and heap[rightChildIdx] >= heap[parentIdx]: return + swap(parentIdx, rightChildIdx) + parentIdx = rightChildIdx + else: + break + leftChildIdx = parentIdx * 2 + 1 + rightChildIdx = parentIdx * 2 + 2 + + +def reheapup(childIdx): + global heap + if childIdx == 0: return + parentIdx = math.floor((childIdx + 1) / 2) - 1 + while abs(heap[parentIdx]) >= abs(heap[childIdx]): + if childIdx == 0: return + if abs(heap[childIdx]) == abs(heap[parentIdx]) and heap[childIdx] >= heap[parentIdx]: return + swap(parentIdx, childIdx) + childIdx = parentIdx + parentIdx = math.floor(childIdx/2) + +def insert(input): + global heap + heap.append(input) + reheapup(len(heap)-1) + +def popMin(): + global heap + if(len(heap)==0): + print(0) + return + if(len(heap)==1): + print(heap.pop()) + return + output = heap[0] + heap[0] = heap.pop() + reheapdown() + print(output) + +N = int(sys.stdin.readline()) + +for i in range(N): + inputNumber = int(sys.stdin.readline()) + if(inputNumber == 0): popMin() + else: insert(inputNumber) \ No newline at end of file diff --git a/src/Do-ho/dataStructor/boj_11286/boj_11286_2.py b/src/Do-ho/dataStructor/boj_11286/boj_11286_2.py new file mode 100644 index 0000000..e87efb5 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_11286/boj_11286_2.py @@ -0,0 +1,13 @@ +import sys +from queue import PriorityQueue + +que = PriorityQueue() + +N = int(sys.stdin.readline()) + +for i in range(N): + x = int(sys.stdin.readline()) + if(x!=0): que.put((abs(x), x)) + else: + if que.empty(): print(0) + else: print(que.get()[1]) \ No newline at end of file From 4ac89d450eb82a794571c9295fdc9aa63618fef5 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 11 Sep 2020 03:08:56 +0900 Subject: [PATCH 026/193] =?UTF-8?q?Add:=20solve=20=ED=94=84=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EB=9E=98=EB=A8=B8=EC=8A=A4=20=EC=9C=84=EC=9E=A5=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dictionary를 통한 풀이 (해시) --- .../pgs_\354\234\204\354\236\245/README.md" | 23 +++++++++++++++++++ .../pgs_\354\234\204\354\236\245.py" | 10 ++++++++ 2 files changed, 33 insertions(+) create mode 100644 "src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/README.md" create mode 100644 "src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.py" diff --git "a/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/README.md" "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/README.md" new file mode 100644 index 0000000..7875641 --- /dev/null +++ "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/README.md" @@ -0,0 +1,23 @@ +## 해시 + +- python에서 hash는 dictionary 형태로 구현 가능하다. + + + +## 아이디어 + +- 처음에는 조합에 대해서 생각을 해봤다. 하지만 부분 집합의 개수를 구하는 데 많은 시간이 걸릴 것 같았다. + +- 다르게 생각을 해보며 몇 개 계산을 해보니 규칙이 눈에 보였다. + + - 의상의 개수가 [2, 2] 일 때 + + > (2+1) * (2+1) - 1 = 8개였다. + + - 의상의 개수가 [2, 2, 3] 일 때 + + > (2+1) * (2+1) * (3+1) - 1= 35개였다. + + - 결국 규칙은 구해온 values 모든 수에 1을 더하고 곱한 뒤 1을 뺀 값이다. + + - 생각을 해보니 입지 않은 경우의 수를 생각해 모든 경우의 수를 구한 뒤 모두 입지 않은 경우의 수인 1개를 빼기만 하면 되는 간단한 구현 문제였던 것 같다. \ No newline at end of file diff --git "a/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.py" "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.py" new file mode 100644 index 0000000..da3cfd5 --- /dev/null +++ "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.py" @@ -0,0 +1,10 @@ +def solution(clothes): + answer = 1 + hash = {} + for item in clothes: + try: hash[item[1]] += 1 + except: hash[item[1]] = 1 + 1 + + for val in list(hash.values()): answer *= val + + return answer - 1 \ No newline at end of file From a411bf71c3a03e53ca43de0b2cab1ea6424613f8 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 11 Sep 2020 03:36:38 +0900 Subject: [PATCH 027/193] Add: solve boj 1991 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 트리를 dictionary 구조를 이용해 풀음 - 재귀적 호출로 풀었음 --- src/Do-ho/dataStructor/boj_1991/README.md | 13 ++++++++ src/Do-ho/dataStructor/boj_1991/boj_1991.py | 36 +++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/Do-ho/dataStructor/boj_1991/README.md create mode 100644 src/Do-ho/dataStructor/boj_1991/boj_1991.py diff --git a/src/Do-ho/dataStructor/boj_1991/README.md b/src/Do-ho/dataStructor/boj_1991/README.md new file mode 100644 index 0000000..73ea5c8 --- /dev/null +++ b/src/Do-ho/dataStructor/boj_1991/README.md @@ -0,0 +1,13 @@ +## 트리 + +- preorder(전위 순회) + - 루트 / 왼쪽 자식 / 오른쪽 자식 +- inorder(중위 순회) + - 왼쪽 자식 / 루트 / 오른쪽 자식 +- postorder(후위 순회) + - 왼쪽 자식 / 오른쪽 자식 / 루트 + + + +- python에서 트리는 어떻게 나타낼 지 모르겠어서 일단 dictionary로 만들었다. +- 만들고 난 뒤 루트 노드인 'A'노드 부터 재귀적으로 값을 저장해주면 될 것 같다는 생각이 들었다. \ No newline at end of file diff --git a/src/Do-ho/dataStructor/boj_1991/boj_1991.py b/src/Do-ho/dataStructor/boj_1991/boj_1991.py new file mode 100644 index 0000000..7955aae --- /dev/null +++ b/src/Do-ho/dataStructor/boj_1991/boj_1991.py @@ -0,0 +1,36 @@ +import sys + +def preorder(ch): + result = '' + if(ch!='.'): + result += ch + result += preorder(tree[ch][0]) + result += preorder(tree[ch][1]) + return result + +def inorder(ch): + result = '' + if(ch!='.'): + result += inorder(tree[ch][0]) + result += ch + result += inorder(tree[ch][1]) + return result + +def postorder(ch): + result = '' + if(ch!='.'): + result += postorder(tree[ch][0]) + result += postorder(tree[ch][1]) + result += ch + return result + +N = int(sys.stdin.readline()) +tree = {} + +for i in range(N): + line = sys.stdin.readline().replace('\n', '').split(' ') + tree[line[0]] = [line[1], line[2]] + +print(preorder('A')) +print(inorder('A')) +print(postorder('A')) \ No newline at end of file From fea975f4a9f6319107a3fdbdd22cc09452247d19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 12 Sep 2020 01:14:14 +0900 Subject: [PATCH 028/193] =?UTF-8?q?solve=20=EC=9C=84=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Main.java" | 20 +++++++++++ .../README.md" | 34 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 "src/kyu9341/programmers_\354\234\204\354\236\245/Main.java" create mode 100644 "src/kyu9341/programmers_\354\234\204\354\236\245/README.md" diff --git "a/src/kyu9341/programmers_\354\234\204\354\236\245/Main.java" "b/src/kyu9341/programmers_\354\234\204\354\236\245/Main.java" new file mode 100644 index 0000000..eb34a81 --- /dev/null +++ "b/src/kyu9341/programmers_\354\234\204\354\236\245/Main.java" @@ -0,0 +1,20 @@ +package programmers42578; + +import java.util.HashMap; + +public class Solution { + + static HashMap map = new HashMap<>(); + + public int solution(String[][] clothes) { + int answer = 1; + for (int i = 0; i < clothes.length; i++) { + if (map.get(clothes[i][1]) == null) map.put(clothes[i][1], 1); + else map.put(clothes[i][1], map.get(clothes[i][1]) + 1); + } + for (String key : map.keySet()) answer *= map.get(key) + 1; + answer--; + return answer; + } + +} diff --git "a/src/kyu9341/programmers_\354\234\204\354\236\245/README.md" "b/src/kyu9341/programmers_\354\234\204\354\236\245/README.md" new file mode 100644 index 0000000..4d4c288 --- /dev/null +++ "b/src/kyu9341/programmers_\354\234\204\354\236\245/README.md" @@ -0,0 +1,34 @@ +# 프로그래머스 - 위장 + +### 문제 링크 + + + +### solve +- 해시 맵을 이용하여 각각 종류별로 몇 개의 의상이 있는지 기록한다. +- 의상의 종류별로 입을 수도 있고 입지 않는 경우도 있으므로 (각 의상의 종류 + 1)을 모두 곱한다. +- 의상을 하나도 입지 않은 경우는 없으므로 마지막에 -1을 해주어야 한다. + +### 코드 +```java +package programmers42578; + +import java.util.HashMap; + +public class Solution { + + static HashMap map = new HashMap<>(); + + public int solution(String[][] clothes) { + int answer = 1; + for (int i = 0; i < clothes.length; i++) { + if (map.get(clothes[i][1]) == null) map.put(clothes[i][1], 1); + else map.put(clothes[i][1], map.get(clothes[i][1]) + 1); + } + for (String key : map.keySet()) answer *= map.get(key) + 1; + answer--; + return answer; + } + +} +``` From 806c6b008b6cc6cef6170688ddf2608c525eff4e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 13 Sep 2020 01:00:57 +0900 Subject: [PATCH 029/193] solve baekjoon 11286 --- src/do02reen24/data-structure/baekjoon_11286.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_11286.py diff --git a/src/do02reen24/data-structure/baekjoon_11286.py b/src/do02reen24/data-structure/baekjoon_11286.py new file mode 100644 index 0000000..e612d4d --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_11286.py @@ -0,0 +1,15 @@ +import sys +import heapq + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + absHeap = [] + for i in range(n): + command = int(sys.stdin.readline()) + if command == 0: + try: + print(heapq.heappop(absHeap)[1]) + except: + print(0) + else: + heapq.heappush(absHeap, (abs(command), command)) \ No newline at end of file From 4bb98d5604adc3f650243a57ff97b4e83b001636 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 13 Sep 2020 02:18:06 +0900 Subject: [PATCH 030/193] solve baekjoon 9012 --- .../data-structure/baekjoon_9012.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_9012.py diff --git a/src/do02reen24/data-structure/baekjoon_9012.py b/src/do02reen24/data-structure/baekjoon_9012.py new file mode 100644 index 0000000..08fbf2d --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_9012.py @@ -0,0 +1,20 @@ +import sys + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + for _ in range(n): + brackets = sys.stdin.readline().rstrip() + result = 'YES' + stack = [] + for bracket in brackets: + if bracket == '(': + stack.append('(') + else: + try: + stack.pop() + except: + result = 'NO' + break + if stack: + result = 'NO' + print(result) \ No newline at end of file From 5e77c926ff1051b1a9691cb1fb6c34f363b0bb9e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 13 Sep 2020 02:58:41 +0900 Subject: [PATCH 031/193] solve baekjoon 1874 --- .../data-structure/baekjoon_1874.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_1874.py diff --git a/src/do02reen24/data-structure/baekjoon_1874.py b/src/do02reen24/data-structure/baekjoon_1874.py new file mode 100644 index 0000000..a1dafe5 --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_1874.py @@ -0,0 +1,30 @@ +import sys + +if __name__ == '__main__': + t = int(sys.stdin.readline()) + stack = [] + count = 1 + result = [] + for _ in range(t): + n = int(sys.stdin.readline()) + check = False + while count <= t: + if stack and stack[-1] == n: + stack.pop() + result.append('-') + check = True + break + stack.append(count) + result.append('+') + count += 1 + if not check and stack: + while stack: + result.append('-') + if n == stack.pop(): + check = True + break + if not check: + print('NO') + sys.exit(0) + for r in result: + print(r) \ No newline at end of file From 09e83c3e0700691b5367bcb21488bd7e661470b3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 13 Sep 2020 04:31:38 +0900 Subject: [PATCH 032/193] solve baekjoon 10799 --- .../data-structure/baekjoon_10799.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/do02reen24/data-structure/baekjoon_10799.py diff --git a/src/do02reen24/data-structure/baekjoon_10799.py b/src/do02reen24/data-structure/baekjoon_10799.py new file mode 100644 index 0000000..378d25c --- /dev/null +++ b/src/do02reen24/data-structure/baekjoon_10799.py @@ -0,0 +1,18 @@ +import sys + +if __name__ == '__main__': + brackets = sys.stdin.readline().rstrip() + stack = [] + result = 0 + for i in range(0, len(brackets)): + if brackets[i] == '(' and brackets[i+1] == ')': + if stack: + stack[-1] += 1 + elif brackets[i] == '(': + stack.append(0) + elif not brackets[i-1] == '(': + laser = stack.pop() + result += laser + 1 + if stack: + stack[-1] += laser + print(result) \ No newline at end of file From f7a3ff679e31fcfd83b5aecac4e09f251714dbc3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 14 Sep 2020 01:04:54 +0900 Subject: [PATCH 033/193] solve baekjoon 1316 --- src/do02reen24/string/baekjoon_1316.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/do02reen24/string/baekjoon_1316.py diff --git a/src/do02reen24/string/baekjoon_1316.py b/src/do02reen24/string/baekjoon_1316.py new file mode 100644 index 0000000..370b877 --- /dev/null +++ b/src/do02reen24/string/baekjoon_1316.py @@ -0,0 +1,20 @@ +import sys + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + count = 0 + for _ in range(n): + word = sys.stdin.readline().rstrip() + check = {} + before = word[0] + for w in word: + if check.get(w) == None: + check[w] = True + before = w + elif before == w: + continue + else: + count -= 1 + break + count += 1 + print(count) \ No newline at end of file From e9534be868b10d4143e57c60442d956563c41fde Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 14 Sep 2020 01:05:47 +0900 Subject: [PATCH 034/193] add : .gitignore --- src/do02reen24/.gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 src/do02reen24/.gitignore diff --git a/src/do02reen24/.gitignore b/src/do02reen24/.gitignore new file mode 100644 index 0000000..9b4e0e7 --- /dev/null +++ b/src/do02reen24/.gitignore @@ -0,0 +1 @@ +카카오코테 \ No newline at end of file From 290fb786326bfeaf0b2e6b06d431d59ac92d4bd6 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Wed, 16 Sep 2020 16:05:07 +0900 Subject: [PATCH 035/193] solve programmers 60057 --- src/do02reen24/string/programmers_60057.py | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/do02reen24/string/programmers_60057.py diff --git a/src/do02reen24/string/programmers_60057.py b/src/do02reen24/string/programmers_60057.py new file mode 100644 index 0000000..af36755 --- /dev/null +++ b/src/do02reen24/string/programmers_60057.py @@ -0,0 +1,41 @@ +def combineString(string, word, count): + if not count == 1: + string += str(count) + string += word + return string + +def compression(string, length): + compString = '' + temp = string[:length] + count = 0 + index = list(range(0, len(string), length)) + for i in index: + now = string[i:i+length] + if now == temp: + count+=1 + else: + compString = combineString(compString, temp, count) + count = 1 + temp = now + if i == index[-1]: + compString = combineString(compString, temp, count) + return len(compString) + +def solution(s): + answer = len(s) + for length in range(1, int(len(s) / 2) + 1): + result = compression(s, length) + if answer > result: + answer = result + return answer + +sList = [ + "aabbaccc", + "ababcdcdababcdcd", + "abcabcdede", + "abcabcabcabcdededededede", + "xababcdcdababcdcd" +] + +for s in sList: + print(solution(s)) \ No newline at end of file From b8f29f3f94140b8f1b0d4135725ed1ca965625c5 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 19 Sep 2020 07:39:45 +0900 Subject: [PATCH 036/193] doc : week2 review --- src/do02reen24/Review/week2.md | 120 +++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 src/do02reen24/Review/week2.md diff --git a/src/do02reen24/Review/week2.md b/src/do02reen24/Review/week2.md new file mode 100644 index 0000000..7d608d5 --- /dev/null +++ b/src/do02reen24/Review/week2.md @@ -0,0 +1,120 @@ +# :fire: week2 + +## :ballot_box_with_check: 백준 11286 +#### 틀렸습니다. + +```python +import sys + +class Num(object): + def __init__(self, n): + self.positive = 0 + self.negative = 0 + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + absStack = {} + min = -1 + for i in range(n): + command = int(sys.stdin.readline()) + if command == 0: + if min == -1: + print(0) + continue + if absStack[min].negative > 0: + print('-'+str(min)) + absStack[min].negative -= 1 + else: + print(min) + absStack[min].positive -= 1 + if absStack[min].negative < 1 and absStack[min].positive < 1: + del absStack[min] + if len(absStack) == 0: + min = -1 + continue + for key in absStack.keys(): + min = key + break + else: + absValue = abs(command) + if not absValue in absStack: + absStack[absValue] = Num(absValue) + if command < 0: + absStack[absValue].negative += 1 + else: + absStack[absValue].positive += 1 + if absValue < min or min < 0: + min = absValue +``` +틀린 이유 key가 순서대로 저장된다고 생각하여 진행하였는데 생각해보니까 삽입 순이기 때문에 고쳐줄 필요가 있었다. + +```python +for key in absStack.keys(): + min = key + break +``` + +`Num` 클래스를 만들어서 진행했는데 굳이 필요없을 것 같아 제거 후 코딩을 진행하였다. + +#### 시간초과 + +```python +import sys + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + absStack = {} + minValue = -1 + for i in range(n): + command = int(sys.stdin.readline()) + if command == 0: + if minValue == -1: + print(0) + continue + + index = minValue * -1 + if not index in absStack: + index = minValue + absStack[index] -= 1 + print(abs(index)) + if absStack[index] < 1: + del absStack[index] + if len(absStack) == 0: + minValue = -1 + continue + minValue = abs(min(list(absStack.keys()), key=abs)) + else: + if not command in absStack: + absStack[command] = 1 + else: + absStack[command] += 1 + if abs(command) < minValue or minValue < 0: + minValue = abs(command) +``` +시간초과가 발생했는데 아마도 `if not index in absStack` 또는 `minValue = abs(min(list(absStack.keys()), key=abs))` 이런 식으로 값을 찾는 부분 때문인 것 같다. + +#### + 두번째 시간초과 + +프로그래머스 위장문제를 풀고 `if not command in absStack:` 을 `if absStack.get(command) == None:` 으로 고쳤으나 결과가 달라지지 않았다. + +#### 맞았습니다. + +문제를 잘못이해해서 heap을 구현하지 않았음을 깨달았다. python에 `heapq` 라는 자료구조가 있음을 알게 되었고 이를 이용해서 문제를 풀었다. + +## :ballot_box_with_check: 프로그래머스 위장 + +쉽게 풀 수 있었다. dict 객체에서 `dict.get(key)` 를 통해 해당 키가 있는지 검사할 수 있음을 알게 되었다. + +```python +if clothesMap.get(c[1]) == None: + clothesMap[c[1]] = [] +clothesMap[c[1]].append(c[0]) +``` + +이런 식으로 key를 검사하도록 코드를 작성하였다. + +## :ballot_box_with_check: 백준 1991 + +python은 `end`를 통해 print문의 끝을 지정해줄 수 있다. `print(index, end='')` 를 통해 결과를 한 줄에 출력하도록 했다. (기본 값 `\n` ) + +## :ballot_box_with_check: 백준 2957(1주차 연장) \ No newline at end of file From 78492872ca3e79f14fa81d7dcfc9b453ee81f56f Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 20 Sep 2020 19:55:49 +0900 Subject: [PATCH 037/193] update : gitignore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit .vscode 설정 제외시키도록 추가 --- src/do02reen24/.gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/do02reen24/.gitignore b/src/do02reen24/.gitignore index 9b4e0e7..24ab719 100644 --- a/src/do02reen24/.gitignore +++ b/src/do02reen24/.gitignore @@ -1 +1,2 @@ -카카오코테 \ No newline at end of file +카카오코테 +.vscode \ No newline at end of file From 6fc276b75e8a0128028d3cc5e331c97cd98caa25 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sun, 20 Sep 2020 20:03:25 +0900 Subject: [PATCH 038/193] =?UTF-8?q?Add:=20Solve=20=EA=B7=B8=EB=A3=B9=20?= =?UTF-8?q?=EC=B2=B4=EC=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Do-ho/string/boj_1316/README.md | 4 ++++ src/Do-ho/string/boj_1316/boj_1316.py | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/Do-ho/string/boj_1316/README.md create mode 100644 src/Do-ho/string/boj_1316/boj_1316.py diff --git a/src/Do-ho/string/boj_1316/README.md b/src/Do-ho/string/boj_1316/README.md new file mode 100644 index 0000000..b54a3d6 --- /dev/null +++ b/src/Do-ho/string/boj_1316/README.md @@ -0,0 +1,4 @@ +# 그룹 단어 체커 + +- 문제를 잘 보니까 이미 나왔던 문자가 다시 나오면 안됨 +- 그래서 맵에 해당 키와 값을 넣고 True/False로 체크 \ No newline at end of file diff --git a/src/Do-ho/string/boj_1316/boj_1316.py b/src/Do-ho/string/boj_1316/boj_1316.py new file mode 100644 index 0000000..104305f --- /dev/null +++ b/src/Do-ho/string/boj_1316/boj_1316.py @@ -0,0 +1,26 @@ +import sys + +N = int(sys.stdin.readline()) + +def checkString(string): + check_arr = {} + prev_char = string[0] + + for ch in string: + try: + if not check_arr[ch]: return False + except: + check_arr[ch] = True + check_arr[prev_char] = False + check_arr[ch] = True + prev_char = ch + + return True + +result = 0 + +for i in range(N): + string = sys.stdin.readline().replace('\n', '') + if checkString(string): result += 1 + +print(result) \ No newline at end of file From a236d2552f411746d4e05e8f5ae341a9fe695a04 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sun, 20 Sep 2020 20:04:56 +0900 Subject: [PATCH 039/193] =?UTF-8?q?Add:=20=EB=AC=B8=EC=9E=90=EC=97=B4=20?= =?UTF-8?q?=EC=95=95=EC=B6=95=20=EB=AC=B8=EC=A0=9C=20=EC=97=85=EB=A1=9C?= =?UTF-8?q?=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../README.md" | 65 +++++++++++++++++++ .../source.py" | 36 ++++++++++ 2 files changed, 101 insertions(+) create mode 100644 "src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/README.md" create mode 100644 "src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/source.py" diff --git "a/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/README.md" "b/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/README.md" new file mode 100644 index 0000000..47a191e --- /dev/null +++ "b/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/README.md" @@ -0,0 +1,65 @@ +# 문자열 압축 + +1. 아이디어 + +```python +for 1글자부터 전체 길이의 반까지 돌림: + prev_str = 첫 글자 선언 + count = 1 + lastcount = 0 + + for 글자 길이 단위로 움직임: + target_str = 타겟 글자 선언 + + if 앞 뒤 글자가 같다면: + count += 1 + if 마지막 검사라면: + lastcount = len(str(count)) + 글자 길이 + elif count가 1이라면: + lastcount = 글자 길이 + else: + # count가 2이상인데 마지막이 아닌 경우 이므로 + lastcount = len(str(count)) + 글자 길이 + +``` + + + +- 1차 시도 실패... + +``` +def solution(s): + answer = 1000 + length = int(len(s) / 2) + 1 + + for i in range(1, length): + prev_str = s[0:i] + count = 1 + lastcount = 0 + prev_j = 0 + for j in range(i, len(s)-i+1 ,i): + target_str = s[j:(j+i)] + print(j) + print(target_str) + if prev_str == target_str: + count+= 1 + if count!=1 and j+i+i>=len(s)-i: + lastcount += len(str(count)) + i + + elif count==1: lastcount += i + else: + lastcount += len(str(count)) + i + count = 1 + prev_str = target_str + prev_j = j + # print(lastcount) + # print(prev_j) + if(prev_j != len(s)-i): + print('ggggggg') + lastcount += len(s)-prev_j + # print(prev_j, lastcount) + if lastcount < answer: answer = lastcount + + return answer +``` + diff --git "a/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/source.py" "b/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/source.py" new file mode 100644 index 0000000..62622a9 --- /dev/null +++ "b/src/Do-ho/string/pgs_\353\254\270\354\236\220\354\227\264\354\225\225\354\266\225/source.py" @@ -0,0 +1,36 @@ +def solution(s): + answer = 1000 + length = int(len(s) / 2) + 1 + + for i in range(1, length): + arr = [] + for j in range(0, len(s)-i+1 ,i): + arr.append(s[j:(j+i)]) + + # 아이템 중복 검사 + prev_item = arr[0] + count = 0 + addcount = 0 + for idx, item in enumerate(arr): + if prev_item == item: + print(prev_item, item) + count += 1 + if(idx==len(arr)-1): + addcount += len(str(count)) + i + elif count==1: + addcount += i + print(prev_item, item) + else: + print(prev_item, item) + addcount += len(str(count)) + i + count = 1 + prev_item = item + + print(i, addcount) + # 스트링 끝까지 검사 안했을 때 + if(len(arr)*i!=len(s)): + addcount += len(s) - (len(arr)*i) + print(i, addcount) + + if addcount < answer: answer = addcount + return answer \ No newline at end of file From bce460c0ee3e2610b7a4338c1302e8f5aca594ce Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 20 Sep 2020 22:41:14 +0900 Subject: [PATCH 040/193] doc : week3 review --- src/do02reen24/Review/week3.md | 119 +++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/do02reen24/Review/week3.md diff --git a/src/do02reen24/Review/week3.md b/src/do02reen24/Review/week3.md new file mode 100644 index 0000000..7585a0d --- /dev/null +++ b/src/do02reen24/Review/week3.md @@ -0,0 +1,119 @@ +# :fire: week3 + +## :ballot_box_with_check: 백준 1316 + +map을 활용하여 쉽게 풀었다. + +## :ballot_box_with_check: 프로그래머스 60057 + +문자열 길이 / 2 만큼 반복문을 돌면서 가장 짧을 때를 찾아주었는데 어떻게 하면 더 효율을 높일 수 있을지 고민해보면 좋을 것 같다. + +## :ballot_box_with_check: 프로그래머스 ​17685 + +#### 시간초과 (18/22) + +```python +def solution(words): + answer = 0 + searchDict = {} + for word in words: + for i in range(len(word)): + w = word[:i+1] + if searchDict.get(w): + searchDict[w] += 1 + else: + searchDict[w] = 1 + + for word in words: + length = len(word) + for i in range(length): + if i+1 == length: + answer += length + break + w = word[:i+1] + if searchDict[w] == 1: + answer += i+1 + break + return answer +``` + +#### 시간초과(18/22) + +``` python +def solution(words): + answer = 0 + searchDict = {} + for word in words: + for i in range(len(word)): + w = word[:i+1] + if searchDict.get(w): + searchDict[w] += 1 + else: + searchDict[w] = 1 + + for word in words: // 1 + length = len(word) + minAnswer = searchDict[word] + ans = length + for i in range(length - 2, -1, -1): + w = word[:i+1] + if minAnswer == 1 and searchDict[w] == minAnswer: + ans = i + 1 + elif searchDict[w] < minAnswer: + minAnswer = searchDict[w] + ans = i + 1 + else: + break + answer += ans + return answer +``` + +1번 제출때와 다르게 뒤에서부터 검사하면 시간을 줄일 수 있지 않을까 했는데 똑같은 경우에서 시간초과가 발생했다. 로직 자체를 다른 방향으로 접근해야하는 것 같다. + +# :fire: 추가문제 + +## :ballot_box_with_check: 백준 9012 + +`brackets = sys.stdin.readline().rstrip()` 에서 rstrip을 꼭 해줘야 했다. 안해줄 경우 공백도 stack에 들어가 연산이 1회 더 수행됐다. + +## :ballot_box_with_check: 백준 1874 + +#### 틀렸습니다. + +```python +import sys + +if __name__ == '__main__': + t = int(sys.stdin.readline()) + stack = [] + number = 1 + result = [] + for _ in range(t): + n = int(sys.stdin.readline()) + while True: + if number > t: + print("NO") + sys.exit(1) + if not stack: + stack.append(number) + else: + top = stack[-1] + if top < n: + number += 1 + stack.append(number) + else: + stack.pop() + result.append('-') + if top == n: + break + continue + result.append('+') + for r in result: + print(r) +``` + +백준 사이트에서는 `sys.exit(0)` 을 써야 오류로 간주되지 않는다고 한다. 나는 `sys.exit(1)` 을 썼다. 새로 제출한 코드는 알고리즘을 바꾸긴 했으나 전체 동작이 동일하므로 아마 exit 함수 때문에 첫번째 시도 때 틀린 것 같다. + +## :ballot_box_with_check: 백준 10799 + +`for i in range(0, len(brackets)):` 의 중간에서 i += 1이 안먹었다. 해결책을 몰라 일단 해당 경우를 skip하는 형태로 코드를 변경하여 제출하였다. python 문법을 좀 더 찾아봐야겠다. \ No newline at end of file From 81df87919dcdb1f4d8ec9ed4d6ab26c573b9998f Mon Sep 17 00:00:00 2001 From: doreen <50297117+do02reen24@users.noreply.github.com> Date: Sun, 20 Sep 2020 23:09:00 +0900 Subject: [PATCH 041/193] Update README.md --- README.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 823c0a1..e17f3b3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # :books: Algorithm Study -## :orange_book: ​알고리즘 사이트 +## :orange_book: 알고리즘 사이트 > 스터디는 다음 알고리즘 사이트에 있는 문제로 진행한다. @@ -25,15 +25,18 @@ ## :green_book: Week Study -| | 1 | 2 | 3 | 4 | -| ----- | :---------------------------------------------------: | :--------------------------------------------: | :---------------------------------------------------: | :----------------------------------------------------: | -| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | +| | 1 | 2 | 3 | 4 | +| ----- | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------: | :----------------------------------------------------------: | +| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | +| 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | +| 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | +| 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | ## :blue_book: Additional Study -| | | | | -| ---- | ---- | ---- | ---- | -| | | | | +| 분류 | | | | +| -------- | -------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | +| 자료구조 | [괄호](https://www.acmicpc.net/problem/9012) | [쇠막대기](https://www.acmicpc.net/problem/10799) | [스택 수열](https://www.acmicpc.net/problem/1874) | @@ -42,4 +45,3 @@ | [grap3fruit](https://github.com/grap3fruit) | [**kyu9341**](https://github.com/kyu9341) | | ----------------------------------------------- | ----------------------------------------- | | [**do02reen24**](https://github.com/do02reen24) | [**Do-ho**](https://github.com/Do-ho) | - From 2b921ffee0e8b0f653d03319b405a5b5f473b31b Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sun, 27 Sep 2020 19:31:40 +0900 Subject: [PATCH 042/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20126?= =?UTF-8?q?0=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dfs / bfs를 통해 해결 --- src/Do-ho/dfsbfs/boj_1260/README.md | 6 ++++ src/Do-ho/dfsbfs/boj_1260/boj_1260.py | 40 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/Do-ho/dfsbfs/boj_1260/README.md create mode 100644 src/Do-ho/dfsbfs/boj_1260/boj_1260.py diff --git a/src/Do-ho/dfsbfs/boj_1260/README.md b/src/Do-ho/dfsbfs/boj_1260/README.md new file mode 100644 index 0000000..fde0e85 --- /dev/null +++ b/src/Do-ho/dfsbfs/boj_1260/README.md @@ -0,0 +1,6 @@ +# DFS와 BFS + +- BFS (너비 우선 탐색) + - queue를 이용해 해당 노드에 연결된 정점들을 정렬 후 추가 +- DFS(깊이 우선 탐색) + - stack을 이용해 해당 노드에 연결된 정점들을 역정렬 후 추가 \ No newline at end of file diff --git a/src/Do-ho/dfsbfs/boj_1260/boj_1260.py b/src/Do-ho/dfsbfs/boj_1260/boj_1260.py new file mode 100644 index 0000000..442b3f2 --- /dev/null +++ b/src/Do-ho/dfsbfs/boj_1260/boj_1260.py @@ -0,0 +1,40 @@ +import sys + +def bfs(graph, start): + visited = [] + queue = [start] + + while queue: + n = queue.pop(0) + if n not in visited: + visited.append(n) + if n in graph: + queue += sorted(graph[n] - set(visited)) + return visited + +def dfs(graph, start): + visited = [] + stack = [start] + + while stack: + n = stack.pop() + if n not in visited: + visited.append(n) + if n in graph: + stack += sorted(graph[n] - set(visited), reverse=True) + return visited + +[N, M, V] = map(int, sys.stdin.readline()[:-1].split(' ')) + +tree = {} + +for i in range(N+1): + tree[i] = set() + +for i in range(M): + [startPoint, endPoint] = list(map(int, sys.stdin.readline()[:-1].split(' '))) + tree[startPoint].add(endPoint) + tree[endPoint].add(startPoint) + +print(" ".join(map(str, dfs(tree, V)))) +print(" ".join(map(str, bfs(tree, V)))) From b86b5f773056d29b10d19c14aed8fcc17ad394c1 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sun, 27 Sep 2020 19:32:14 +0900 Subject: [PATCH 043/193] =?UTF-8?q?Add:=20upload=20=EB=B0=B1=EC=A4=80=2019?= =?UTF-8?q?238=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 아직 미해결했지만 업로드 - 추후 해결 --- src/Do-ho/dfsbfs/boj_19238/README.md | 32 +++++++++++++++++++++++++ src/Do-ho/dfsbfs/boj_19238/boj_19238.py | 32 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/Do-ho/dfsbfs/boj_19238/README.md create mode 100644 src/Do-ho/dfsbfs/boj_19238/boj_19238.py diff --git a/src/Do-ho/dfsbfs/boj_19238/README.md b/src/Do-ho/dfsbfs/boj_19238/README.md new file mode 100644 index 0000000..7cf4bb0 --- /dev/null +++ b/src/Do-ho/dfsbfs/boj_19238/README.md @@ -0,0 +1,32 @@ +# 스타트 택시 + +- 맵에다가 해당 사람을 표현 + +- 1은 벽, 2와 -2를 동시에 표현해 시작점과 도착점을 표기 + + - 이렇게 할 경우 겹칠 위험이 있을듯 + - 따라서 맵에 넣고 비교하는 것도 좋을듯 + +- 길 찾기 알고리즘으로 bfs를 채택 + + - 모든 맵을 찾지 않고 중간에 break 가능할까? + + ```python + def bfs(graph, start): + visited = [] + queue = [start] + + while queue: + n = queue.pop(0) + if n not in visited: + visited.append(n) + if n in graph: + queue += sorted(graph[n] - set(visited)) + return visited + ``` + + - 재귀 구조가 아니라서 가능할 것 같음! + - 어디로 움직일 지에 대한 설계가 필요 + + - + diff --git a/src/Do-ho/dfsbfs/boj_19238/boj_19238.py b/src/Do-ho/dfsbfs/boj_19238/boj_19238.py new file mode 100644 index 0000000..271d780 --- /dev/null +++ b/src/Do-ho/dfsbfs/boj_19238/boj_19238.py @@ -0,0 +1,32 @@ +import sys + +# N : 활동 영역(가로 * 세로) +# M : 승객의 수 +# fuel : 처음 소지한 연료 +[N, M, fuel] = map(int, sys.stdin.readline()[:-1].split(' ')) + +road = [] + +# 길 입력 +for i in range(N): + appendArr = list(map(int, sys.stdin.readline()[:-1].split(' '))) + road.append(appendArr) + +# 택시 처음 좌표 입력 +[taxiX, texiY] = map(int, sys.stdin.readline()[:-1].split(' ')) + +# 손님 위치 및 목적지 입력 +for i in range(M): + cus = list(map(int, sys.stdin.readline()[:-1].split(' '))) + road[cus[0]-1][cus[1]-1] = i+2 + road[cus[2]-1][cus[3]-1] = -(i+2) + +print(road) + +def dfs(startPoint, endPoint): + num = 0 + + # if(startPoint[0]>=endPoint[0]): + + + return num \ No newline at end of file From b2515deb38207903fe29cbd1f03f7a1d104dd6d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Sep 2020 12:25:52 +0900 Subject: [PATCH 044/193] solve 7569 --- src/kyu9341/7569/Main.java | 118 +++++++++++++++++++++++++++++++++ src/kyu9341/7569/README.md | 132 +++++++++++++++++++++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 src/kyu9341/7569/Main.java create mode 100644 src/kyu9341/7569/README.md diff --git a/src/kyu9341/7569/Main.java b/src/kyu9341/7569/Main.java new file mode 100644 index 0000000..3aef283 --- /dev/null +++ b/src/kyu9341/7569/Main.java @@ -0,0 +1,118 @@ +package boj7569; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + + static int n, m, h; + static int dx[] = { 1, -1, 0, 0, 0, 0 }; + static int dy[] = { 0, 0, 1, -1, 0, 0 }; + static int dz[] = { 0, 0, 0, 0, 1, -1 }; + + static int tomato[][][]; + static int dist[][][]; + static Queue q = new LinkedList<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + m = Integer.parseInt(st.nextToken()); + n = Integer.parseInt(st.nextToken()); + h = Integer.parseInt(st.nextToken()); + + tomato = new int[n][m][h]; + dist = new int[n][m][h]; + initArr(dist, -1); + + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < m; j++) { + tomato[i][j][k] = Integer.parseInt(st.nextToken()); + if (tomato[i][j][k] == 1) { + q.add(new Location(i ,j , k)); + dist[i][j][k] = 0; + } + } + } + } + + while(!q.isEmpty()) { + Location cur = q.poll(); + + for (int i = 0; i < 6; i++) { + int nx = cur.x + dx[i]; + int ny = cur.y + dy[i]; + int nz = cur.z + dz[i]; + + if (isRange(nx, ny, nz) && tomato[nx][ny][nz] == 0 && dist[nx][ny][nz] == -1) { + tomato[nx][ny][nz] = 1; + dist[nx][ny][nz] = dist[cur.x][cur.y][cur.z] + 1; + q.add(new Location(nx, ny, nz)); + } + } + } + + + if (!checkTomato()) { + System.out.println(-1); + return; + } + + System.out.println(getMax()); + + } + + static boolean checkTomato() { + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (tomato[i][j][k] == 0) return false; + } + } + } + return true; + } + + static int getMax() { + int max = 0; + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (dist[i][j][k] > max) max = dist[i][j][k]; + } + } + } + return max; + } + + static boolean isRange(int x, int y, int z) { + return x >= 0 && y >= 0 && z >= 0 && x < n && y < m && z < h; + } + + static void initArr(int arr[][][], int val) { + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + arr[i][j][k] = val; + } + } + } + } + + static class Location { + int x, y, z; + + public Location(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + } +} diff --git a/src/kyu9341/7569/README.md b/src/kyu9341/7569/README.md new file mode 100644 index 0000000..ca927e7 --- /dev/null +++ b/src/kyu9341/7569/README.md @@ -0,0 +1,132 @@ +# Problem 7569 + +## 토마토 + +### 문제 링크 + + + +### solve +- 토마토가 하루에 앞, 뒤, 좌, 우, 위, 아래로 영향을 주므로 z축을 추가하여 6방향으로 전파시킨다. +- bfs 이후에 익지 않은 토마토가 있으면 -1, 아니면 최대dist값을 출력한다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + + static int n, m, h; + static int dx[] = { 1, -1, 0, 0, 0, 0 }; + static int dy[] = { 0, 0, 1, -1, 0, 0 }; + static int dz[] = { 0, 0, 0, 0, 1, -1 }; + + static int tomato[][][]; + static int dist[][][]; + static Queue q = new LinkedList<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + m = Integer.parseInt(st.nextToken()); + n = Integer.parseInt(st.nextToken()); + h = Integer.parseInt(st.nextToken()); + + tomato = new int[n][m][h]; + dist = new int[n][m][h]; + initArr(dist, -1); + + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < m; j++) { + tomato[i][j][k] = Integer.parseInt(st.nextToken()); + if (tomato[i][j][k] == 1) { + q.add(new Location(i ,j , k)); + dist[i][j][k] = 0; + } + } + } + } + + while(!q.isEmpty()) { + Location cur = q.poll(); + + for (int i = 0; i < 6; i++) { + int nx = cur.x + dx[i]; + int ny = cur.y + dy[i]; + int nz = cur.z + dz[i]; + + if (isRange(nx, ny, nz) && tomato[nx][ny][nz] == 0 && dist[nx][ny][nz] == -1) { + tomato[nx][ny][nz] = 1; + dist[nx][ny][nz] = dist[cur.x][cur.y][cur.z] + 1; + q.add(new Location(nx, ny, nz)); + } + } + } + + + if (!checkTomato()) { + System.out.println(-1); + return; + } + + System.out.println(getMax()); + + } + + static boolean checkTomato() { + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (tomato[i][j][k] == 0) return false; + } + } + } + return true; + } + + static int getMax() { + int max = 0; + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (dist[i][j][k] > max) max = dist[i][j][k]; + } + } + } + return max; + } + + static boolean isRange(int x, int y, int z) { + return x >= 0 && y >= 0 && z >= 0 && x < n && y < m && z < h; + } + + static void initArr(int arr[][][], int val) { + for (int k = 0; k < h; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + arr[i][j][k] = val; + } + } + } + } + + static class Location { + int x, y, z; + + public Location(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + } +} + +``` From 6fd14f390ec044f5dbf0558b3ab597b4cc639747 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Sep 2020 12:26:15 +0900 Subject: [PATCH 045/193] solve 2606 --- src/kyu9341/2606/Main.java | 56 +++++++++++++++++++++++++++++++ src/kyu9341/2606/README.md | 68 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 src/kyu9341/2606/Main.java create mode 100644 src/kyu9341/2606/README.md diff --git a/src/kyu9341/2606/Main.java b/src/kyu9341/2606/Main.java new file mode 100644 index 0000000..15b9c5e --- /dev/null +++ b/src/kyu9341/2606/Main.java @@ -0,0 +1,56 @@ +package boj2606; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class Main { + + static int n, m; + static ArrayList> net = new ArrayList<>(); + static boolean check[]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + m = Integer.parseInt(br.readLine()); + + check = new boolean[n + 1]; + + for (int i = 0; i <= n; i++) { + net.add(new ArrayList<>()); + } + + for (int i = 0; i < m; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int u = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + + net.get(u).add(v); + net.get(v).add(u); + } + + dfs(1); + + int cnt = 0; + for (int i = 1; i <= n; i++) { + if (check[i]) cnt++; + } + + System.out.println(cnt - 1); + } + + static void dfs(int node) { + if (check[node]) return; + check[node] = true; + + for (int i = 0; i < net.get(node).size(); i++) { + int next = net.get(node).get(i); + if (!check[next]) { + dfs(next); + } + } + } +} diff --git a/src/kyu9341/2606/README.md b/src/kyu9341/2606/README.md new file mode 100644 index 0000000..5f51e58 --- /dev/null +++ b/src/kyu9341/2606/README.md @@ -0,0 +1,68 @@ +# Problem 2606 + +## 바이러스 + +### 문제 링크 + + +### solve +- 먼저 컴퓨터를 모두 연결시킨 후 dfs로 1번 컴퓨터와 연결된 컴퓨터를 모두 구한다. + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class Main { + + static int n, m; + static ArrayList> net = new ArrayList<>(); + static boolean check[]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + m = Integer.parseInt(br.readLine()); + + check = new boolean[n + 1]; + + for (int i = 0; i <= n; i++) { + net.add(new ArrayList<>()); + } + + for (int i = 0; i < m; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int u = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + + net.get(u).add(v); + net.get(v).add(u); + } + + dfs(1); + + int cnt = 0; + for (int i = 1; i <= n; i++) { + if (check[i]) cnt++; + } + + System.out.println(cnt - 1); + } + + static void dfs(int node) { + if (check[node]) return; + check[node] = true; + + for (int i = 0; i < net.get(node).size(); i++) { + int next = net.get(node).get(i); + if (!check[next]) { + dfs(next); + } + } + } +} + +``` From 02776ac458cfdea24aa190816db6a560e8680374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Sep 2020 12:26:30 +0900 Subject: [PATCH 046/193] solve 1697 --- src/kyu9341/1697/Main.java | 58 +++++++++++++++++++++++++++++++ src/kyu9341/1697/README.md | 71 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 src/kyu9341/1697/Main.java create mode 100644 src/kyu9341/1697/README.md diff --git a/src/kyu9341/1697/Main.java b/src/kyu9341/1697/Main.java new file mode 100644 index 0000000..6146d05 --- /dev/null +++ b/src/kyu9341/1697/Main.java @@ -0,0 +1,58 @@ +package boj1697; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + + static final int MAX = 100000; + static int n, k; + static boolean check[] = new boolean[MAX + 1]; + static int sec[] = new int[MAX + 1]; + + 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()); + k = Integer.parseInt(st.nextToken()); + + Queue q = new LinkedList<>(); + + q.add(n); + check[n] = true; + sec[n] = 0; + + while(!q.isEmpty()) { + int cur = q.poll(); + + if (check[k]) break; + + if (cur * 2 <= MAX && !check[cur * 2]) { + check[cur * 2] = true; + sec[cur * 2] = sec[cur] + 1; + q.add(cur * 2); + } + + if (cur + 1 <= MAX && !check[cur + 1]) { + check[cur + 1] = true; + sec[cur + 1] = sec[cur] + 1; + q.add(cur + 1); + } + + if (cur - 1 >= 0 && !check[cur - 1]) { + check[cur - 1] = true; + sec[cur - 1] = sec[cur] + 1; + q.add(cur - 1); + } + } + + System.out.println(sec[k]); + + } + +} diff --git a/src/kyu9341/1697/README.md b/src/kyu9341/1697/README.md new file mode 100644 index 0000000..e0abece --- /dev/null +++ b/src/kyu9341/1697/README.md @@ -0,0 +1,71 @@ +# Problem 1697 + +## 숨바꼭질 + +### 문제 링크 + + + +### solve +- x + 1, x - 1, x * 2 로 bfs + +### 코드 설명 +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +public class Main { + + static final int MAX = 100000; + static int n, k; + static boolean check[] = new boolean[MAX + 1]; + static int sec[] = new int[MAX + 1]; + + 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()); + k = Integer.parseInt(st.nextToken()); + + Queue q = new LinkedList<>(); + + q.add(n); + check[n] = true; + sec[n] = 0; + + while(!q.isEmpty()) { + int cur = q.poll(); + + if (check[k]) break; + + if (cur * 2 <= MAX && !check[cur * 2]) { + check[cur * 2] = true; + sec[cur * 2] = sec[cur] + 1; + q.add(cur * 2); + } + + if (cur + 1 <= MAX && !check[cur + 1]) { + check[cur + 1] = true; + sec[cur + 1] = sec[cur] + 1; + q.add(cur + 1); + } + + if (cur - 1 >= 0 && !check[cur - 1]) { + check[cur - 1] = true; + sec[cur - 1] = sec[cur] + 1; + q.add(cur - 1); + } + } + + System.out.println(sec[k]); + + } + +} + +``` From e1e22c9f015278b130e867048a94f43abb2de4e8 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 2 Oct 2020 22:42:50 +0900 Subject: [PATCH 047/193] =?UTF-8?q?Rename:=20=ED=8F=B4=EB=8D=94=20?= =?UTF-8?q?=EC=9D=B4=EB=A6=84=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/README.md" | 0 .../Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/boj_1260.py" | 0 .../README.md" | 0 .../boj_19238.py" | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename src/Do-ho/dfsbfs/boj_1260/README.md => "src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/README.md" (100%) rename src/Do-ho/dfsbfs/boj_1260/boj_1260.py => "src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/boj_1260.py" (100%) rename src/Do-ho/dfsbfs/boj_19238/README.md => "src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/README.md" (100%) rename src/Do-ho/dfsbfs/boj_19238/boj_19238.py => "src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/boj_19238.py" (100%) diff --git a/src/Do-ho/dfsbfs/boj_1260/README.md "b/src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/README.md" similarity index 100% rename from src/Do-ho/dfsbfs/boj_1260/README.md rename to "src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/README.md" diff --git a/src/Do-ho/dfsbfs/boj_1260/boj_1260.py "b/src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/boj_1260.py" similarity index 100% rename from src/Do-ho/dfsbfs/boj_1260/boj_1260.py rename to "src/Do-ho/dfsbfs/boj_1260_DFS\354\231\200BFS/boj_1260.py" diff --git a/src/Do-ho/dfsbfs/boj_19238/README.md "b/src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/README.md" similarity index 100% rename from src/Do-ho/dfsbfs/boj_19238/README.md rename to "src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/README.md" diff --git a/src/Do-ho/dfsbfs/boj_19238/boj_19238.py "b/src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/boj_19238.py" similarity index 100% rename from src/Do-ho/dfsbfs/boj_19238/boj_19238.py rename to "src/Do-ho/dfsbfs/boj_19238_\354\212\244\355\203\200\355\212\270\355\203\235\354\213\234/boj_19238.py" From f7fb6bdf3dcfc28050aa98db482e9ba15edb24d7 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 2 Oct 2020 22:43:35 +0900 Subject: [PATCH 048/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20169?= =?UTF-8?q?7=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bfs를 통해 해결 --- .../README.md" | 74 +++++++++++++++++++ .../boj_1697.py" | 27 +++++++ 2 files changed, 101 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/README.md" create mode 100644 "src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/boj_1697.py" diff --git "a/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/README.md" "b/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/README.md" new file mode 100644 index 0000000..552d1a3 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/README.md" @@ -0,0 +1,74 @@ +# 숨바꼭질 + +##### 1. 재귀를 통한 풀이 + +```python +import sys + +maxCount = 100001 + +def search(start, end, count): + global maxCount + if(count>=maxCount): + return + if start==end: + if maxCount>=count: + maxCount = count + return + elif (end*2)<=start: + return + elif start<=-1: + return + else: + if start==0: + search(start+1, end, count+1) + if start < end: + search(start*2, end, count+1) + search(start+1, end, count+1) + search(start-1, end, count+1) + else: + count += end-start + return + +[N, K] = map(int, sys.stdin.readline()[:-1].split(' ')) +search(N, K, 0) + +print(maxCount) +``` +- 해당 풀이는 재귀의 호출이 너무 많아 런타임이 나옴 + + + +##### 2. bfs를 통한 풀이 + +```python +import sys + +checkList = [False for i in range(100001)] + +def search(start, end): + global checkList + + queue = [(start, 0)] + + while len(queue)!=0: + target = queue.pop(0) + if target[0] > 100000 or target[0] < 0: continue + if checkList[target[0]]: continue + + checkList[target[0]] = True + + if target[0] == end: + print(target[1]) + break + + queue.append((target[0]*2, target[1] + 1)) + queue.append((target[0]-1, target[1] + 1)) + queue.append((target[0]+1, target[1] + 1)) + +[N, K] = map(int, sys.stdin.readline()[:-1].split(' ')) + +search(N, K) +``` + +- bfs를 통해 가장 먼저 찾아지는 카운트를 활용 \ No newline at end of file diff --git "a/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/boj_1697.py" "b/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/boj_1697.py" new file mode 100644 index 0000000..d113a7e --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_1697_\354\210\250\353\260\224\352\274\255\354\247\210/boj_1697.py" @@ -0,0 +1,27 @@ +import sys + +checkList = [False for i in range(100001)] + +def search(start, end): + global checkList + + queue = [(start, 0)] + + while len(queue)!=0: + target = queue.pop(0) + if target[0] > 100000 or target[0] < 0: continue + if checkList[target[0]]: continue + + checkList[target[0]] = True + + if target[0] == end: + print(target[1]) + break + + queue.append((target[0]*2, target[1] + 1)) + queue.append((target[0]-1, target[1] + 1)) + queue.append((target[0]+1, target[1] + 1)) + +[N, K] = map(int, sys.stdin.readline()[:-1].split(' ')) + +search(N, K) \ No newline at end of file From ed4ecada984814329d6d207998b8ca2f2bb2a490 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 2 Oct 2020 22:43:56 +0900 Subject: [PATCH 049/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20260?= =?UTF-8?q?6=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bfs를 통한 풀이 --- .../README.md" | 3 +++ .../boj_2606.py" | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/README.md" create mode 100644 "src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/boj_2606.py" diff --git "a/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/README.md" "b/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/README.md" new file mode 100644 index 0000000..e7defb7 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/README.md" @@ -0,0 +1,3 @@ +# 바이러스 + +- bfs로 가뿐하게 통과~~!! \ No newline at end of file diff --git "a/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/boj_2606.py" "b/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/boj_2606.py" new file mode 100644 index 0000000..a14d86d --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2606_\353\260\224\354\235\264\353\237\254\354\212\244/boj_2606.py" @@ -0,0 +1,27 @@ +import sys + +def bfs(graph, start): + visited = [] + queue = [start] + + while len(queue)!=0: + target = queue.pop(0) + if target not in visited: + visited.append(target) + for item in graph[target]: + queue.append(item) + return len(visited)-1 + +computerNum = int(sys.stdin.readline()[:-1]) +lineNum = int(sys.stdin.readline()[:-1]) +graph = {} + +for i in range(lineNum): + [node1, node2] = map(int, sys.stdin.readline()[:-1].split(' ')) + try: graph[node1].append(node2) + except: graph[node1] = [node2] + + try: graph[node2].append(node1) + except: graph[node2] = [node1] + +print(bfs(graph, 1)) \ No newline at end of file From 595f400ee77815b4b18a06ec297affe643c7bce5 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Fri, 2 Oct 2020 22:45:07 +0900 Subject: [PATCH 050/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20756?= =?UTF-8?q?9=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - BFS를 통한 풀이 - 안 익은 토마토를 세는 것보다 익은 토마토를 세는 것이 더 빨랐음 --- .../README.md" | 273 ++++++++++++++++++ .../boj_7569.py" | 65 +++++ .../boj_7569_2.py" | 47 +++ 3 files changed, 385 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/README.md" create mode 100644 "src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569.py" create mode 100644 "src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569_2.py" diff --git "a/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/README.md" "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/README.md" new file mode 100644 index 0000000..e764a8f --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/README.md" @@ -0,0 +1,273 @@ +# 토마토 + +1. 입력 중에 0이 없으면 0 반환 +2. 안익은 토마토에 대해서 돌면서 가장 가까운 1까지의 최단 경로 구하기 + - 만약 1을 못찾으면 1반환 + - 최단 경로 중 방문했던 곳은 방문 인해도 됨. (아마도..?) + - 결국 최단 경로가 가장 큰 것이 답이 될듯 + +- 1번째풀이 [시간 초과] +```python +import sys + +directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + +[M, N, H] = map(int, sys.stdin.readline()[:-1].split(' ')) + +tomato = [] + +for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline()[:-1].split(' ')))) + tomato.append(tmp) + +def function(): + underripeTomatos = [] + isAllRipeTomatos = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + underripeTomatos.append((i, j, k)) + isAllRipeTomatos = False + + if isAllRipeTomatos: return 0 + + days = 0 # 아무 값 + + while(len(underripeTomatos)!=0): + visited = [] + target = underripeTomatos.pop(0) + if target not in visited: + tmp = isExistGoodTomato(target, visited) + if tmp == 0: return -1 + if days <= tmp: days = tmp + + return days + +def isExistGoodTomato(underripeTomato, parentvisited): + visited = [] + queue = [(underripeTomato, 1)] + while len(queue) != 0: + tmp = queue.pop(0) + target = tmp[0] + count = tmp[1] + if target not in visited: + visited.append(target) + for direction in directions: + x = target[2] + direction[2] + y = target[1] + direction[1] + z = target[0] + direction[0] + + if x<0 or y<0 or z<0 or x>=M or y>=N or z>=H: continue + elif tomato[z][y][x] == 1: return count + elif tomato[z][y][x] == -1: continue + else: + if (x, y, z) not in parentvisited: parentvisited.append((x, y, z)) + queue.append(((z, y, x), count + 1)) + return 0 + +print(function()) +``` + +- 2번째풀이 [시간 초과] + - 느낌 상 visited에 대한 탐색 비용이 많이 들어서 그런 것 같아서 배열 마킹 방법으로 변경 + +```python +import sys + +directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + +[M, N, H] = map(int, sys.stdin.readline()[:-1].split(' ')) + +tomato = [] + +for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline()[:-1].split(' ')))) + tomato.append(tmp) + +def function(): + underripeTomatos = [] + isAllRipeTomatos = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + underripeTomatos.append((i, j, k)) + isAllRipeTomatos = False + + if isAllRipeTomatos: return 0 + + days = 0 # 아무 값 + + while(len(underripeTomatos)!=0): + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + target = underripeTomatos.pop(0) + if not visited[target[0]][target[1]][target[2]]: + tmp = isExistGoodTomato(target, visited) + if tmp == 0: return -1 + if days <= tmp: days = tmp + + return days + +def isExistGoodTomato(underripeTomato, parentvisited): + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + queue = [(underripeTomato, 1)] + while len(queue) != 0: + tmp = queue.pop(0) + target = tmp[0] + count = tmp[1] + if not visited[target[0]][target[1]][target[2]]: + visited[target[0]][target[1]][target[2]] = True + for direction in directions: + x = target[2] + direction[2] + y = target[1] + direction[1] + z = target[0] + direction[0] + + if x<0 or y<0 or z<0 or x>=M or y>=N or z>=H: continue + elif tomato[z][y][x] == 1: return count + elif tomato[z][y][x] == -1: continue + else: + if not parentvisited[z][y][x]: parentvisited[z][y][x] = True + queue.append(((z, y, x), count + 1)) + return 0 + +print(function()) +``` + +- 3번째풀이 [시간 초과] + - 그래도 같아서.. 뭐가 문제지... ㅠㅠㅠ + - pop(0)의 비용은 얼마일까 보니 O(n) 그래서 나온 것이 ```deque.popleft()``` + +```python +import sys +from collections import deque + +directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + +[M, N, H] = map(int, sys.stdin.readline()[:-1].split(' ')) + +tomato = [] + +for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline()[:-1].split(' ')))) + tomato.append(tmp) + +def function(): + underripeTomatos = deque() + isAllRipeTomatos = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + underripeTomatos.append((i, j, k)) + isAllRipeTomatos = False + + if isAllRipeTomatos: return 0 + + days = 0 # 아무 값 + + while(len(underripeTomatos)!=0): + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + target = underripeTomatos.popleft() + if not visited[target[0]][target[1]][target[2]]: + tmp = isExistGoodTomato(target, visited) + if tmp == 0: return -1 + if days <= tmp: days = tmp + + return days + +def isExistGoodTomato(underripeTomato, parentvisited): + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + queue = deque() + queue.append((underripeTomato, 1)) + + while len(queue) != 0: + tmp = queue.popleft() + target = tmp[0] + count = tmp[1] + if not visited[target[0]][target[1]][target[2]]: + visited[target[0]][target[1]][target[2]] = True + for direction in directions: + x = target[2] + direction[2] + y = target[1] + direction[1] + z = target[0] + direction[0] + + if x<0 or y<0 or z<0 or x>=M or y>=N or z>=H: continue + elif tomato[z][y][x] == 1: return count + elif tomato[z][y][x] == -1: continue + else: + if not parentvisited[z][y][x]: parentvisited[z][y][x] = True + queue.append(((z, y, x), count + 1)) + return 0 + +print(function()) +``` + +- 4번째 풀이 [성공 ㅠㅠ] + + - 알고리즘의 변화 + - 그냥 익혀보자 안익은거 찾지말아보자 + - 위의 복잡도가 은근 큰 것 같다.... + + ```python + import sys + from collections import deque + + directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + + [M, N, H] = map(int, sys.stdin.readline().split()) + + tomato = [] + + for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline().split()))) + tomato.append(tmp) + + def function(): + ripeTomatos = deque() + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 1: + ripeTomatos.append((i, j, k, 0)) + + day = 0 + + while ripeTomatos: + z, y, x, day = ripeTomatos.popleft() + if tomato[z][y][x]==0: tomato[z][y][x] = 1 + for dx, dy, dz in directions: + nx, ny, nz = x+dx, y+dy, z+dz + if nx<0 or ny<0 or nz<0 or nx>=M or ny>=N or nz>=H: continue + if tomato[nz][ny][nx] == 0: + if not visited[nz][ny][nx]: + ripeTomatos.append((nz, ny, nx, day+1)) + visited[nz][ny][nx] = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + return -1 + + return day + + sys.stdout.write(str(function())) + ``` + + + +위에서 리팩토링을 많이 했는데 다음 게시물을 참고함 [[참고](https://www.acmicpc.net/blog/view/70)] \ No newline at end of file diff --git "a/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569.py" "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569.py" new file mode 100644 index 0000000..08ecc1b --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569.py" @@ -0,0 +1,65 @@ +import sys +from collections import deque + +directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + +[M, N, H] = map(int, sys.stdin.readline()[:-1].split(' ')) + +tomato = [] + +for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline()[:-1].split(' ')))) + tomato.append(tmp) + +def function(): + underripeTomatos = deque() + isAllRipeTomatos = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + underripeTomatos.append((i, j, k)) + isAllRipeTomatos = False + + if isAllRipeTomatos: return 0 + + days = 0 + + while underripeTomatos: + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + target = underripeTomatos.popleft() + if not visited[target[0]][target[1]][target[2]]: + tmp = isExistGoodTomato(target, visited) + if tmp == 0: return -1 + if days <= tmp: days = tmp + + return days + +def isExistGoodTomato(underripeTomato, parentvisited): + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + queue = deque() + queue.append((underripeTomato, 1)) + + while queue: + tmp = queue.popleft() + target = tmp[0] + count = tmp[1] + if not visited[target[0]][target[1]][target[2]]: + visited[target[0]][target[1]][target[2]] = True + for direction in directions: + x = target[2] + direction[2] + y = target[1] + direction[1] + z = target[0] + direction[0] + + if x<0 or y<0 or z<0 or x>=M or y>=N or z>=H: continue + elif tomato[z][y][x] == 1: return count + elif tomato[z][y][x] == -1: continue + else: + if not parentvisited[z][y][x]: parentvisited[z][y][x] = True + if not visited[z][y][z]: queue.append(((z, y, x), count + 1)) + return 0 + +sys.stdout.write(str(function())) \ No newline at end of file diff --git "a/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569_2.py" "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569_2.py" new file mode 100644 index 0000000..8bf38b8 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_7569_\355\206\240\353\247\210\355\206\240/boj_7569_2.py" @@ -0,0 +1,47 @@ +import sys +from collections import deque + +directions = [(-1, 0, 0), (1, 0, 0), (0, -1, 0), (0, 1, 0), (0, 0, -1), (0, 0, 1)] + +[M, N, H] = map(int, sys.stdin.readline().split()) + +tomato = [] + +for i in range(H): + tmp = [] + for j in range(N): + tmp.append(list(map(int, sys.stdin.readline().split()))) + tomato.append(tmp) + +def function(): + ripeTomatos = deque() + visited = [[[False for i in range(M)] for i in range(N)] for i in range(H)] + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 1: + ripeTomatos.append((i, j, k, 0)) + + day = 0 + + while ripeTomatos: + z, y, x, day = ripeTomatos.popleft() + if tomato[z][y][x]==0: tomato[z][y][x] = 1 + for dx, dy, dz in directions: + nx, ny, nz = x+dx, y+dy, z+dz + if nx<0 or ny<0 or nz<0 or nx>=M or ny>=N or nz>=H: continue + if tomato[nz][ny][nx] == 0: + if not visited[nz][ny][nx]: + ripeTomatos.append((nz, ny, nx, day+1)) + visited[nz][ny][nx] = True + + for i in range(H): + for j in range(N): + for k in range(M): + if tomato[i][j][k] == 0: + return -1 + + return day + +sys.stdout.write(str(function())) \ No newline at end of file From 4e1d4a7cf4fa363d2daad10fb64636e92daa7b85 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Fri, 2 Oct 2020 22:50:20 +0900 Subject: [PATCH 051/193] Update README.md --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e17f3b3..5163fc2 100644 --- a/README.md +++ b/README.md @@ -31,12 +31,14 @@ | 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | | 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | | 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | +| 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | ## :blue_book: Additional Study -| 분류 | | | | -| -------- | -------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | -| 자료구조 | [괄호](https://www.acmicpc.net/problem/9012) | [쇠막대기](https://www.acmicpc.net/problem/10799) | [스택 수열](https://www.acmicpc.net/problem/1874) | +| 분류 | | | | +| -------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | +| 자료구조 | [괄호](https://www.acmicpc.net/problem/9012) | [쇠막대기](https://www.acmicpc.net/problem/10799) | [스택 수열](https://www.acmicpc.net/problem/1874) | +| BFS/DFS | [DFS와 BFS](https://www.acmicpc.net/problem/1260) | | | From ed37af44e5ada44084f74f70c4ae7ed94029dba3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 07:05:15 +0900 Subject: [PATCH 052/193] doc : week3 review update --- src/do02reen24/Review/week3.md | 55 +++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/src/do02reen24/Review/week3.md b/src/do02reen24/Review/week3.md index 7585a0d..f7102ea 100644 --- a/src/do02reen24/Review/week3.md +++ b/src/do02reen24/Review/week3.md @@ -51,7 +51,7 @@ def solution(words): else: searchDict[w] = 1 - for word in words: // 1 + for word in words: length = len(word) minAnswer = searchDict[word] ans = length @@ -70,6 +70,59 @@ def solution(words): 1번 제출때와 다르게 뒤에서부터 검사하면 시간을 줄일 수 있지 않을까 했는데 똑같은 경우에서 시간초과가 발생했다. 로직 자체를 다른 방향으로 접근해야하는 것 같다. +#### 시간초과(18/22) + +마땅한 해결책이 떠오르지 않아 인터넷 검색을 통해 해결하였다. `트라이` 자료구조의 활용을 의도한 문제라고 한다. + +[Trie 자료구조 의미와 활용](https://blog.ilkyu.kr/entry/%ED%8C%8C%EC%9D%B4%EC%8D%AC%EC%97%90%EC%84%9C-Trie-%ED%8A%B8%EB%9D%BC%EC%9D%B4-%EA%B5%AC%ED%98%84%ED%95%98%EA%B8%B0) 을 통해 Trie에 대해 자세히 알 수 있었다. + +**방법 1. Trie** + +* 트리 자료 구조의 일종으로 어떤 문자열을 검색할 때의 시간 복잡도는 **O(n)** 이다. (n은 문자열의 최대 길이) + +* 문자열 검색에 특화된 자료구조이다. + +Trie를 사용해 더 이상 단어의 분기점이 없는 지점을 찾는 과정을 통해 문제를 해결 할 수 있다. + +**방법 2. 전체 단어의 사전 순 정렬** + +전체 단어를 사전순으로 정렬하면 인접한 두 단어 쌍만 비교하여 문제를 빠르게 해결할 수 있다. + +**내 코드는 왜 시간초과일까?** + +Trie를 구현하는 방법은 여러가지가 있어 여러 풀이를 찾아봤는데 내가 구현한 것과 큰 차이를 모르겠었다. 어떤 부분에서 시간초과가 발생한 것일까? + +[dictionary 시간복잡도](https://wayhome25.github.io/python/2017/06/14/time-complexity/) 를 찾아봤지만 `index`, `get` 모두 `O(1)` 이었다. + +**`list`의 `slice` 때문인가?** Trie와 내가 구현한 것의 차이를 생각해보니 Trie는 list의 다음 요소를 검사할 뿐이지만, 내가 구현한 코드는 앞의 문자열을 만들기 때문에 `O(n)` 의 시간복잡도로 검사할 다음 문자열을 생성하게 된다. 즉 `w = word[:i+1]` 부분이 문제인줄 알고 해당 부분을 고쳐서 돌려보았으나 똑같이 **시간초과가 발생**했다. + +```python +def solution(words): + answer = 0 + searchDict = {} + for word in words: + index = '' + for w in word: + index += w + if searchDict.get(index): + searchDict[index] += 1 + else: + searchDict[index] = 1 + + for word in words: + index = '' + length = len(word) + for i in range(length): + if i+1 == length: + answer += length + break + index += word[i] + if searchDict[index] == 1: + answer += i+1 + break + return answer +``` + # :fire: 추가문제 ## :ballot_box_with_check: 백준 9012 From 173a68e8606a11ab632ee7991f4115aac371219e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 07:05:24 +0900 Subject: [PATCH 053/193] doc : week4 review update --- src/do02reen24/Review/week4.md | 103 +++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/do02reen24/Review/week4.md diff --git a/src/do02reen24/Review/week4.md b/src/do02reen24/Review/week4.md new file mode 100644 index 0000000..ffbde9e --- /dev/null +++ b/src/do02reen24/Review/week4.md @@ -0,0 +1,103 @@ +# :fire: week4 + +## :ballot_box_with_check: 백준 19238 + +#### 틀렸습니다. + +```python +import sys + +dr = [-1, 1, 0, 0] +dc = [0, 0, -1, 1] + +class Passenger(object): + def __init__(self, row, col, destRow, destCol): + self.row = row + self.col = col + self.destRow = destRow + self.destCol = destCol + +def pickUpPassenger(board, row, col, n): + newBoard = [[0]*n for _ in range(n)] + queue = [] + count = 0 + queue.append([row, col]) + newBoard[row][col] = -1 + while queue: + count += 1 + newQueue = [] + while queue: + r, c = queue.pop() + for i in range(0, 4): + mr = r + dr[i] + mc = c + dc[i] + if mr >= 0 and mr < n and mc >=0 and mc < n: + if board[mr][mc] > 0: + return board[mr][mc] - 1, count + if not board[mr][mc] == -1 and newBoard[mr][mc] == 0: + newBoard[mr][mc] = count + newQueue.append([mr, mc]) + queue = newQueue + return -1, -1 + +def goDestination(board, row, col, destRow, destCol, n): + newBoard = [[0]*n for _ in range(n)] + queue = [] + count = 0 + queue.append([row, col]) + newBoard[row][col] = -1 + while queue: + count += 1 + newQueue = [] + while queue: + r, c = queue.pop() + for i in range(0, 4): + mr = r + dr[i] + mc = c + dc[i] + if mr == destRow and mc == destCol: + return count + if mr >= 0 and mr < n and mc >=0 and mc < n: + if board[mr][mc] == 0: + newBoard[mr][mc] = count + newQueue.append([mr, mc]) + queue = newQueue + +def moveLocation(n): + return int(n) - 1 + +def TaxiService(): + n, m, fuel = map(int, sys.stdin.readline().split()) + board = [] + for _ in range(n): + board.append(list(map(int, sys.stdin.readline().replace('1', '-1').split()))) + + taxiRow, taxiCol = map(moveLocation, sys.stdin.readline().split()) + passengers = [] + for i in range(1, m+1): + row, col, destRow, destCol = map(moveLocation, sys.stdin.readline().split()) + board[row][col] = i + passengers.append(Passenger(row, col, destRow, destCol)) + while m > 0: + if board[taxiRow][taxiCol] > 0: + board[taxiRow][taxiCol] = 0 + else: + index, count = pickUpPassenger(board, taxiRow, taxiCol, n) + fuel -= count + if fuel < 0 or count == -1: + return -1 + taxiRow = passengers[index].row + taxiCol = passengers[index].col + board[taxiRow][taxiCol] = 0 + fee = goDestination(board, taxiRow, taxiCol, passengers[index].destRow, passengers[index].destCol, n) + fuel -= fee + if fuel < 0: + return -1 + taxiRow = passengers[index].destRow + taxiCol = passengers[index].destCol + fuel += fee*2 + m -= 1 + return fuel + +if __name__ == '__main__': + print(TaxiService()) +``` From 6347da87c7ea5afd6c9da5f89cd18f5771dad154 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 07:05:47 +0900 Subject: [PATCH 054/193] solve baekjoon 1697 --- src/do02reen24/BFS/baekjoon_1697.cpp | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/do02reen24/BFS/baekjoon_1697.cpp diff --git a/src/do02reen24/BFS/baekjoon_1697.cpp b/src/do02reen24/BFS/baekjoon_1697.cpp new file mode 100644 index 0000000..6b0c9c1 --- /dev/null +++ b/src/do02reen24/BFS/baekjoon_1697.cpp @@ -0,0 +1,44 @@ +#include +#include +using namespace std; +const int MAX_RANGE = 2000000; +bool visit[MAX_RANGE + 1]; +int cost[MAX_RANGE + 1]; +int main() { + int n, k; + cin >> n >> k; + queue q; + cost[n] = 0; + visit[n] = true; + q.push(n); + while (!q.empty()) { + int index = q.front(); + q.pop(); + if (index - 1 >= 0) { + if (visit[index - 1] == false) { + q.push(index - 1); + visit[index - 1] = true; + cost[index - 1] = cost[index] + 1; + } + } + if (index + 1 < MAX_RANGE) { + if (visit[index + 1] == false) { + q.push(index + 1); + visit[index + 1] = true; + cost[index + 1] = cost[index] + 1; + } + } + if (index * 2 < MAX_RANGE) { + if (visit[index * 2] == false) { + q.push(index * 2); + visit[index * 2] = true; + cost[index * 2] = cost[index] + 1; + } + } + if (visit[k] == true) { + cout << cost[k] << '\n'; + break; + } + } + return 0; +} \ No newline at end of file From 37e4cf47467a574b761aa18e2873c6f1ba735426 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 07:26:32 +0900 Subject: [PATCH 055/193] solve baekjoon 2606 --- src/do02reen24/BFS/baekjoon_2606.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/do02reen24/BFS/baekjoon_2606.py diff --git a/src/do02reen24/BFS/baekjoon_2606.py b/src/do02reen24/BFS/baekjoon_2606.py new file mode 100644 index 0000000..fd98d29 --- /dev/null +++ b/src/do02reen24/BFS/baekjoon_2606.py @@ -0,0 +1,29 @@ +import sys + +if __name__ == '__main__': + ans = 0 + n = int(sys.stdin.readline()) + t = int(sys.stdin.readline()) + network = {} + for _ in range(t): + n1, n2 = map(int, sys.stdin.readline().split()) + if network.get(n1) == None: + network[n1] = [] + network[n1].append(n2) + if network.get(n2) == None: + network[n2] = [] + network[n2].append(n1) + visit = [False] * (n + 1) + queue = [] + queue.append(1) + visit[1] = True + while queue: + index = queue.pop() + check = network[index] + while check: + com = check.pop() + if visit[com] == False: + queue.append(com) + visit[com] = True + ans += 1 + print(ans) \ No newline at end of file From e5d3085339eaf1890ccf0f7e7123ef0dbd1d5b3b Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 08:06:53 +0900 Subject: [PATCH 056/193] solve baekjoon 7569 --- src/do02reen24/BFS/baekjoon_7569.py | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/do02reen24/BFS/baekjoon_7569.py diff --git a/src/do02reen24/BFS/baekjoon_7569.py b/src/do02reen24/BFS/baekjoon_7569.py new file mode 100644 index 0000000..96e8330 --- /dev/null +++ b/src/do02reen24/BFS/baekjoon_7569.py @@ -0,0 +1,48 @@ +import sys + +dh = [-1, 1, 0, 0, 0, 0] +dr = [0, 0, -1, 1, 0, 0] +dc = [0, 0, 0, 0, -1, 1] + +def getDays(): + n, m, k = map(int, sys.stdin.readline().split()) + ans = 0 + boxes = [] + remain = 0 + tomatoes = [] + for height in range(0, k): + box = [] + for row in range(0, m): + t = list(map(int, sys.stdin.readline().split())) + box.append(t) + for col in range(0, len(t)): + if t[col] == 0: + remain += 1 + elif t[col] == 1: + tomatoes.append((height, row, col)) + boxes.append(box) + if remain == 0: + return 0 + if not tomatoes: + return -1 + newTomatoes = [] + while tomatoes: + h, r, c = tomatoes.pop() + for i in range(0, 6): + mh = h + dh[i] + mr = r + dr[i] + mc = c + dc[i] + if mh >=0 and mh < k and mr >=0 and mr < m and mc >=0 and mc < n: + if boxes[mh][mr][mc] == 0: + boxes[mh][mr][mc] = 1 + remain -= 1 + newTomatoes.append((mh, mr, mc)) + if not tomatoes and newTomatoes: + tomatoes = newTomatoes + newTomatoes = [] + ans += 1 + if remain > 0: + return -1 + return ans +if __name__ == '__main__': + print(getDays()) \ No newline at end of file From ebb79cd577e45d836ae8975713435f8e334f3b92 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 3 Oct 2020 08:09:01 +0900 Subject: [PATCH 057/193] doc : week5 review update --- src/do02reen24/Review/week5.md | 100 +++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/do02reen24/Review/week5.md diff --git a/src/do02reen24/Review/week5.md b/src/do02reen24/Review/week5.md new file mode 100644 index 0000000..035f2e2 --- /dev/null +++ b/src/do02reen24/Review/week5.md @@ -0,0 +1,100 @@ +# :fire: week5 + +## :ballot_box_with_check: 백준 1697 + +#### 메모리 초과 + +```python +import sys + +n, k = map(int, sys.stdin.readline().split()) + +board = {} +board[n] = 0 +queue = [] +newQueue = [] +count = 1 +queue.append(n) +while queue: + index = queue.pop() + if board.get(index-1) == None: + newQueue.append(index-1) + board[index-1] = count + if board.get(index+1) == None: + newQueue.append(index+1) + board[index+1] = count + if board.get(index*2) == None: + newQueue.append(index*2) + board[index*2] = count + if board.get(k): + print(board[k]) + break + if not queue: + queue = newQueue + newQueue = [] + count += 1 +``` + +`dict` 자료구조를 사용하고 max 범위를 걸어주지 않아 생긴 에러인듯 하다. + +#### 틀렸습니다. + +```c++ +#include +#include + +using namespace std; +const int MAX_RANGE = 2000000; +int visit[MAX_RANGE]; + +int main() { + int n, k; + cin >> n >> k; + queue q; + queue q2; + visit[n] = -1; + q.push(n); + int count = 1; + + while (!q.empty()) { + int index = q.front(); + q.pop(); + if (index - 1 >= 0) { + if (visit[index - 1] == 0) { + q2.push(index - 1); + visit[index - 1] = count; + } + } + if (index + 1 < MAX_RANGE) { + if (visit[index + 1] == 0) { + q2.push(index + 1); + visit[index + 1] = count; + } + } + if (index * 2 < MAX_RANGE) { + if (visit[index * 2] == 0) { + q2.push(index * 2); + visit[index * 2] = count; + } + } + if (visit[k] != 0) { + cout << visit[k] << '\n'; + break; + } + if (q.empty()) { + q = q2; + q2 = queue(); + count++; + } + } + return 0; +} +``` + +## :ballot_box_with_check: 백준 2606 + +map 과 list를 활용하여 쉽게 풀었다. + +## :ballot_box_with_check: 백준 7569 + +6가지 방향에 대해 검사를 해주고 예외 조건들을 확인하는 식으로 해결하였다. \ No newline at end of file From 26440bcf34dad2705bd162c3c04b34d678ac54a4 Mon Sep 17 00:00:00 2001 From: doreen <50297117+do02reen24@users.noreply.github.com> Date: Sat, 3 Oct 2020 10:53:15 +0900 Subject: [PATCH 058/193] =?UTF-8?q?week6=20=EB=AC=B8=EC=A0=9C=20=EC=97=85?= =?UTF-8?q?=EB=8D=B0=EC=9D=B4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit week6는 분할과 정복입니다. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5163fc2..4feb2ce 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ | 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | | 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | | 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | +| 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | ## :blue_book: Additional Study From 14866f564ac40d06ca704403e01748d254601a80 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 9 Oct 2020 16:10:00 +0900 Subject: [PATCH 059/193] solve : baekjoon 1992 --- src/do02reen24/Review/week6.md | 59 +++++++++++++++++++ .../divide-and-conquer/baekjoon_1992.py | 44 ++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 src/do02reen24/Review/week6.md create mode 100644 src/do02reen24/divide-and-conquer/baekjoon_1992.py diff --git a/src/do02reen24/Review/week6.md b/src/do02reen24/Review/week6.md new file mode 100644 index 0000000..1844e75 --- /dev/null +++ b/src/do02reen24/Review/week6.md @@ -0,0 +1,59 @@ +# :fire: week6 + +## :ballot_box_with_check: 백준 1992 + +#### 출력 초과 + +```python +import sys + +board = [] + +def checkBoard(startRow, endRow, startCol, endCol): + check = board[startRow][startCol] + for r in range(startRow, endRow): + for c in range(startCol, endCol): + if not check == board[r][c]: return False + return True + +def compress(n, startRow, startCol): + n = int(n / 2) + ans = [] + print(n, startRow, startCol) + if checkBoard(startRow, startRow + n, startCol, startCol + n): + ans.append(board[startRow][startCol]) + else: + ans.append(compress(n, startRow, startCol)) + if checkBoard(startRow, startRow + n, startCol + n, startCol + n + n): + ans.append(board[startRow][startCol + n]) + else: + ans.append(compress(n, startRow, startCol + n)) + if checkBoard(startRow + n, startRow + n + n, startCol, startCol + n): + ans.append(board[startRow + n][startCol]) + else: + ans.append(compress(n, startRow + n, startCol)) + if checkBoard(startRow + n, startRow + n + n, startCol + n, startCol + n + n): + ans.append(board[startRow + n][startCol + n]) + else: + ans.append(compress(n, startRow + n, startCol + n)) + return '(' + ''.join(ans) + ')' + +def findSolution(N): + if checkBoard(0, N, 0, N): + return board[0][0] + ans = compress(N, 0, 0) + return ans + +if __name__ == '__main__': + N = int(sys.stdin.readline()) + for i in range(N): + inputs = list(sys.stdin.readline().rstrip()) + board.append(inputs) + print(findSolution(N)) +``` + +확인용으로 찍어놓은 print문을 지우지 않아서 발생한 문제였다. 앞으로는 더 꼼꼼하게 확인하도록 해야겠다. + +## :ballot_box_with_check: 백준 2630 + +## :ballot_box_with_check: 백준 1780 diff --git a/src/do02reen24/divide-and-conquer/baekjoon_1992.py b/src/do02reen24/divide-and-conquer/baekjoon_1992.py new file mode 100644 index 0000000..e226a51 --- /dev/null +++ b/src/do02reen24/divide-and-conquer/baekjoon_1992.py @@ -0,0 +1,44 @@ +import sys + +board = [] + +def checkBoard(startRow, endRow, startCol, endCol): + check = board[startRow][startCol] + for r in range(startRow, endRow): + for c in range(startCol, endCol): + if not check == board[r][c]: return False + return True + +def compress(n, startRow, startCol): + n = int(n / 2) + ans = [] + if checkBoard(startRow, startRow + n, startCol, startCol + n): + ans.append(board[startRow][startCol]) + else: + ans.append(compress(n, startRow, startCol)) + if checkBoard(startRow, startRow + n, startCol + n, startCol + n + n): + ans.append(board[startRow][startCol + n]) + else: + ans.append(compress(n, startRow, startCol + n)) + if checkBoard(startRow + n, startRow + n + n, startCol, startCol + n): + ans.append(board[startRow + n][startCol]) + else: + ans.append(compress(n, startRow + n, startCol)) + if checkBoard(startRow + n, startRow + n + n, startCol + n, startCol + n + n): + ans.append(board[startRow + n][startCol + n]) + else: + ans.append(compress(n, startRow + n, startCol + n)) + return '(' + ''.join(ans) + ')' + +def findSolution(N): + if checkBoard(0, N, 0, N): + return board[0][0] + ans = compress(N, 0, 0) + return ans + +if __name__ == '__main__': + N = int(sys.stdin.readline()) + for i in range(N): + inputs = list(sys.stdin.readline().rstrip()) + board.append(inputs) + print(findSolution(N)) \ No newline at end of file From 7622a737b5af754312f9316f1cf5d410654a1f10 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 9 Oct 2020 16:25:10 +0900 Subject: [PATCH 060/193] solve : baekjoon 2630 --- src/do02reen24/Review/week6.md | 2 + .../divide-and-conquer/baekjoon_2630.py | 49 +++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/do02reen24/divide-and-conquer/baekjoon_2630.py diff --git a/src/do02reen24/Review/week6.md b/src/do02reen24/Review/week6.md index 1844e75..162c512 100644 --- a/src/do02reen24/Review/week6.md +++ b/src/do02reen24/Review/week6.md @@ -56,4 +56,6 @@ if __name__ == '__main__': ## :ballot_box_with_check: 백준 2630 +1992 문제와 유사하여 빠르게 풀 수 있었다. + ## :ballot_box_with_check: 백준 1780 diff --git a/src/do02reen24/divide-and-conquer/baekjoon_2630.py b/src/do02reen24/divide-and-conquer/baekjoon_2630.py new file mode 100644 index 0000000..36f4993 --- /dev/null +++ b/src/do02reen24/divide-and-conquer/baekjoon_2630.py @@ -0,0 +1,49 @@ +import sys + +board = [] +blue = 0 +white = 0 + +def checkBoard(startRow, endRow, startCol, endCol): + check = board[startRow][startCol] + for r in range(startRow, endRow): + for c in range(startCol, endCol): + if not check == board[r][c] : return False + global blue + global white + if check == 1: blue = blue + 1 + elif check == 0: white = white + 1 + return True + +def compress(n, startRow, startCol): + n = int(n / 2) + ans = [] + if checkBoard(startRow, startRow + n, startCol, startCol + n): + ans.append(board[startRow][startCol]) + else: + ans.append(compress(n, startRow, startCol)) + if checkBoard(startRow, startRow + n, startCol + n, startCol + n + n): + ans.append(board[startRow][startCol + n]) + else: + ans.append(compress(n, startRow, startCol + n)) + if checkBoard(startRow + n, startRow + n + n, startCol, startCol + n): + ans.append(board[startRow + n][startCol]) + else: + ans.append(compress(n, startRow + n, startCol)) + if checkBoard(startRow + n, startRow + n + n, startCol + n, startCol + n + n): + ans.append(board[startRow + n][startCol + n]) + else: + ans.append(compress(n, startRow + n, startCol + n)) + +def findSolution(N): + if checkBoard(0, N, 0, N): return + compress(N, 0, 0) + +if __name__ == '__main__': + N = int(sys.stdin.readline().rstrip()) + for _ in range(N): + inputs = list(map(int, sys.stdin.readline().split(' '))) + board.append(inputs) + findSolution(N) + print(white) + print(blue) \ No newline at end of file From 32c4b1ff10881a14a2aac940b550164ed6c072e3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 9 Oct 2020 16:56:14 +0900 Subject: [PATCH 061/193] refactor : baekjoon 2630 --- .../divide-and-conquer/baekjoon_2630.py | 25 ++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/src/do02reen24/divide-and-conquer/baekjoon_2630.py b/src/do02reen24/divide-and-conquer/baekjoon_2630.py index 36f4993..b431a2d 100644 --- a/src/do02reen24/divide-and-conquer/baekjoon_2630.py +++ b/src/do02reen24/divide-and-conquer/baekjoon_2630.py @@ -17,23 +17,14 @@ def checkBoard(startRow, endRow, startCol, endCol): def compress(n, startRow, startCol): n = int(n / 2) - ans = [] - if checkBoard(startRow, startRow + n, startCol, startCol + n): - ans.append(board[startRow][startCol]) - else: - ans.append(compress(n, startRow, startCol)) - if checkBoard(startRow, startRow + n, startCol + n, startCol + n + n): - ans.append(board[startRow][startCol + n]) - else: - ans.append(compress(n, startRow, startCol + n)) - if checkBoard(startRow + n, startRow + n + n, startCol, startCol + n): - ans.append(board[startRow + n][startCol]) - else: - ans.append(compress(n, startRow + n, startCol)) - if checkBoard(startRow + n, startRow + n + n, startCol + n, startCol + n + n): - ans.append(board[startRow + n][startCol + n]) - else: - ans.append(compress(n, startRow + n, startCol + n)) + if not checkBoard(startRow, startRow + n, startCol, startCol + n): + compress(n, startRow, startCol) + if not checkBoard(startRow, startRow + n, startCol + n, startCol + n + n): + compress(n, startRow, startCol + n) + if not checkBoard(startRow + n, startRow + n + n, startCol, startCol + n): + compress(n, startRow + n, startCol) + if not checkBoard(startRow + n, startRow + n + n, startCol + n, startCol + n + n): + compress(n, startRow + n, startCol + n) def findSolution(N): if checkBoard(0, N, 0, N): return From 1396473b9c3a50d4e4abaea267bf783548e0fd55 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 9 Oct 2020 16:57:28 +0900 Subject: [PATCH 062/193] solve : baekjoon 1780 --- src/do02reen24/Review/week6.md | 2 + .../divide-and-conquer/baekjoon_1780.py | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/do02reen24/divide-and-conquer/baekjoon_1780.py diff --git a/src/do02reen24/Review/week6.md b/src/do02reen24/Review/week6.md index 162c512..ea6d8fb 100644 --- a/src/do02reen24/Review/week6.md +++ b/src/do02reen24/Review/week6.md @@ -59,3 +59,5 @@ if __name__ == '__main__': 1992 문제와 유사하여 빠르게 풀 수 있었다. ## :ballot_box_with_check: 백준 1780 + +2630 문제와 유사했다. /2 가 아닌 /3 을 해야한다는 점만 조금 달랐다. \ No newline at end of file diff --git a/src/do02reen24/divide-and-conquer/baekjoon_1780.py b/src/do02reen24/divide-and-conquer/baekjoon_1780.py new file mode 100644 index 0000000..c42586b --- /dev/null +++ b/src/do02reen24/divide-and-conquer/baekjoon_1780.py @@ -0,0 +1,43 @@ +import sys + +board = [] + +minus = 0 +zero = 0 +plus = 0 + +def checkBoard(startRow, endRow, startCol, endCol): + check = board[startRow][startCol] + for r in range(startRow, endRow): + for c in range(startCol, endCol): + if not check == board[r][c]: return False + global minus + global zero + global plus + if check == -1: minus += 1 + elif check == 0: zero += 1 + elif check == 1: plus += 1 + return True + +def makeRange(n): + return[[0,0],[0,n],[0,2*n],[n,0],[n,n],[n,2*n],[2*n,0],[2*n,n],[2*n,2*n]] + +def compress(n, startRow, startCol): + n = int(n / 3) + ranges = makeRange(n) + for r, c in ranges: + if not checkBoard(startRow + r, startRow + r + n, startCol + c, startCol + c + n): compress(n, startRow + r, startCol + c) + +def findSolution(n): + if checkBoard(0, n, 0, n): return + compress(n, 0, 0) + +if __name__ == '__main__': + n = int(sys.stdin.readline()) + for _ in range(0, n): + inputs = list(map(int, sys.stdin.readline().split(' '))) + board.append(inputs) + findSolution(n) + print(minus) + print(zero) + print(plus) \ No newline at end of file From 9723b9f9ce531a82bac88efcf132f216e115f80b Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 10 Oct 2020 02:06:39 +0900 Subject: [PATCH 063/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20263?= =?UTF-8?q?0=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 분할정복법을 통한 풀이 --- .../boj_2630.py" | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 "src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" diff --git "a/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" new file mode 100644 index 0000000..77dbb1e --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" @@ -0,0 +1,59 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + white = 0 + blue = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == 0: white += 1 + else: blue += 1 + + if white==A: return 0 + elif blue==A: return 1 + else: return -1 + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +N = int(sys.stdin.readline()) + +paper = [] +white_paper = 0 +blue_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: white_paper +=1 + elif status == 1: blue_paper += 1 + else: + queue.extend(divide(target)) + +print(white_paper) +print(blue_paper) \ No newline at end of file From 04a6de1ec46b6e88a72ee02cb99fb014ec9d15de Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 10 Oct 2020 02:06:51 +0900 Subject: [PATCH 064/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20199?= =?UTF-8?q?2=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 분할정복법을 통한 풀이 --- .../boj_1992.py" | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 "src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" diff --git "a/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" new file mode 100644 index 0000000..344c380 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" @@ -0,0 +1,60 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + one = 0 + zero = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '1': one += 1 + else: zero += 1 + + if one==A: return '1' + elif zero==A: return '0' + else: return '-1' + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +def quad(arr): + result = "" + status = conquer(arr) + + if status == '0': result += "0" + elif status == '1': result += "1" + else: + result += "(" + dividearr = divide(arr) + for da in dividearr: + result += quad(da) + result += ")" + return result + +N = int(sys.stdin.readline()) + +video = [] + +for i in range(N): + value = sys.stdin.readline() + video.append(value) + +sys.stdout.write(quad(video)) \ No newline at end of file From 19c91ff3486de913e813a55a155e8653c9e3ae20 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 10 Oct 2020 02:06:59 +0900 Subject: [PATCH 065/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20178?= =?UTF-8?q?0=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 분할정복법을 통한 풀이 --- .../README.md" | 226 ++++++++++++++++++ .../boj_1780.py" | 69 ++++++ 2 files changed, 295 insertions(+) create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" new file mode 100644 index 0000000..8538798 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" @@ -0,0 +1,226 @@ +# 종이의 개수 + +- 첫 번째 시도 (메모리 초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == -1: minus_one += 1 + elif arr[i][j] == 0: zero += 1 + else: one += 1 + + if minus_one==A: return -1 + elif zero==A: return 0 + elif one==A: return 1 + else: return 2 + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +N = int(sys.stdin.readline()) + +paper = [] +minus_one_paper = 0 +one_paper = 0 +zero_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: zero_paper +=1 + elif status == 1: one_paper += 1 + elif status == -1: minus_one_paper += 1 + else: + queue.extend(divide(target)) + +sys.stdout.write(str(minus_one_paper)+'\n') +sys.stdout.write(str(zero_paper)+'\n') +sys.stdout.write(str(one_paper)+'\n') +``` + +- 두 번째 시도(시간초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '-1': minus_one += 1 + elif arr[i][j] == '0': zero += 1 + else: one += 1 + + if minus_one==A: return '-1' + elif zero==A: return '0' + elif one==A: return '1' + else: return '2' + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` + +- 세 번째 시도(성공) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" new file mode 100644 index 0000000..5353c61 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" @@ -0,0 +1,69 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') \ No newline at end of file From 6bba6637e14c86ab36dcccbf221b92eba27808a4 Mon Sep 17 00:00:00 2001 From: doreen <50297117+do02reen24@users.noreply.github.com> Date: Sat, 10 Oct 2020 11:05:10 +0900 Subject: [PATCH 066/193] =?UTF-8?q?7=EC=A3=BC=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=EC=97=85=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7주차는 비트마스킹입니다. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4feb2ce..6f35bdb 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ | 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | | 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | | 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | +| 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | ## :blue_book: Additional Study From bc6bebe61f95d608128c058891b4909dc3c1b54a Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Sat, 10 Oct 2020 11:29:10 +0900 Subject: [PATCH 067/193] =?UTF-8?q?[week6]=20=EB=B6=84=ED=95=A0=EC=A0=95?= =?UTF-8?q?=EB=B3=B5=EB=B2=95=20(#17)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 --- .../README.md" | 226 ++++++++++++++++++ .../boj_1780.py" | 69 ++++++ .../boj_1992.py" | 60 +++++ .../boj_2630.py" | 59 +++++ 4 files changed, 414 insertions(+) create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" create mode 100644 "src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" create mode 100644 "src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" new file mode 100644 index 0000000..8538798 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" @@ -0,0 +1,226 @@ +# 종이의 개수 + +- 첫 번째 시도 (메모리 초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == -1: minus_one += 1 + elif arr[i][j] == 0: zero += 1 + else: one += 1 + + if minus_one==A: return -1 + elif zero==A: return 0 + elif one==A: return 1 + else: return 2 + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +N = int(sys.stdin.readline()) + +paper = [] +minus_one_paper = 0 +one_paper = 0 +zero_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: zero_paper +=1 + elif status == 1: one_paper += 1 + elif status == -1: minus_one_paper += 1 + else: + queue.extend(divide(target)) + +sys.stdout.write(str(minus_one_paper)+'\n') +sys.stdout.write(str(zero_paper)+'\n') +sys.stdout.write(str(one_paper)+'\n') +``` + +- 두 번째 시도(시간초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '-1': minus_one += 1 + elif arr[i][j] == '0': zero += 1 + else: one += 1 + + if minus_one==A: return '-1' + elif zero==A: return '0' + elif one==A: return '1' + else: return '2' + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` + +- 세 번째 시도(성공) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" new file mode 100644 index 0000000..5353c61 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" @@ -0,0 +1,69 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" new file mode 100644 index 0000000..344c380 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" @@ -0,0 +1,60 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + one = 0 + zero = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '1': one += 1 + else: zero += 1 + + if one==A: return '1' + elif zero==A: return '0' + else: return '-1' + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +def quad(arr): + result = "" + status = conquer(arr) + + if status == '0': result += "0" + elif status == '1': result += "1" + else: + result += "(" + dividearr = divide(arr) + for da in dividearr: + result += quad(da) + result += ")" + return result + +N = int(sys.stdin.readline()) + +video = [] + +for i in range(N): + value = sys.stdin.readline() + video.append(value) + +sys.stdout.write(quad(video)) \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" new file mode 100644 index 0000000..77dbb1e --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" @@ -0,0 +1,59 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + white = 0 + blue = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == 0: white += 1 + else: blue += 1 + + if white==A: return 0 + elif blue==A: return 1 + else: return -1 + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +N = int(sys.stdin.readline()) + +paper = [] +white_paper = 0 +blue_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: white_paper +=1 + elif status == 1: blue_paper += 1 + else: + queue.extend(divide(target)) + +print(white_paper) +print(blue_paper) \ No newline at end of file From 0e946a0c9eef7a795a254d2923432008bcb59ba9 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Sat, 10 Oct 2020 11:29:28 +0900 Subject: [PATCH 068/193] =?UTF-8?q?[week6]=20=EB=B6=84=ED=95=A0=EC=A0=95?= =?UTF-8?q?=EB=B3=B5=EB=B2=95=20(#17)=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 --- .../README.md" | 226 ++++++++++++++++++ .../boj_1780.py" | 69 ++++++ .../boj_1992.py" | 60 +++++ .../boj_2630.py" | 59 +++++ 4 files changed, 414 insertions(+) create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" create mode 100644 "src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" create mode 100644 "src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" create mode 100644 "src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" new file mode 100644 index 0000000..8538798 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/README.md" @@ -0,0 +1,226 @@ +# 종이의 개수 + +- 첫 번째 시도 (메모리 초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == -1: minus_one += 1 + elif arr[i][j] == 0: zero += 1 + else: one += 1 + + if minus_one==A: return -1 + elif zero==A: return 0 + elif one==A: return 1 + else: return 2 + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +N = int(sys.stdin.readline()) + +paper = [] +minus_one_paper = 0 +one_paper = 0 +zero_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: zero_paper +=1 + elif status == 1: one_paper += 1 + elif status == -1: minus_one_paper += 1 + else: + queue.extend(divide(target)) + +sys.stdout.write(str(minus_one_paper)+'\n') +sys.stdout.write(str(zero_paper)+'\n') +sys.stdout.write(str(one_paper)+'\n') +``` + +- 두 번째 시도(시간초과) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + minus_one = 0 + zero = 0 + one = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '-1': minus_one += 1 + elif arr[i][j] == '0': zero += 1 + else: one += 1 + + if minus_one==A: return '-1' + elif zero==A: return '0' + elif one==A: return '1' + else: return '2' + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` + +- 세 번째 시도(성공) +```python +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') +``` \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" new file mode 100644 index 0000000..5353c61 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1780_\354\242\205\354\235\264\354\235\230\352\260\234\354\210\230/boj_1780.py" @@ -0,0 +1,69 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + + if A==1: return arr[0][0] + + check = arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] != check: return "-2" + + return check + +def divide(arr): + L = len(arr) + + area = [deque() for i in range(9)] + k = int(L/3) + + for i in range(0, k): + area[0].append(arr[i][:k]) + area[1].append(arr[i][k:2*k]) + area[2].append(arr[i][2*k:]) + for i in range(k, 2*k): + area[3].append(arr[i][:k]) + area[4].append(arr[i][k:2*k]) + area[5].append(arr[i][2*k:]) + for i in range(2*k, L): + area[6].append(arr[i][:k]) + area[7].append(arr[i][k:2*k]) + area[8].append(arr[i][2*k:]) + + return area + +def f(arr): + minus_one_paper = 0 + zero_paper = 0 + one_paper = 0 + + status = conquer(arr) + if status == '0': zero_paper +=1 + elif status == '1': one_paper += 1 + elif status == '-1': minus_one_paper += 1 + else: + dividearr = divide(arr) + for da in dividearr: + result = f(da) + minus_one_paper += result[0] + zero_paper += result[1] + one_paper += result[2] + + return [minus_one_paper, zero_paper, one_paper] + +N = int(sys.stdin.readline()) + +paper = [] + +for i in range(N): + paper.append(sys.stdin.readline().split()) + +papernum = f(paper) + +sys.stdout.write(str(papernum[0])+'\n') +sys.stdout.write(str(papernum[1])+'\n') +sys.stdout.write(str(papernum[2])+'\n') \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" new file mode 100644 index 0000000..344c380 --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_1992_\354\277\274\353\223\234\355\212\270\353\246\254/boj_1992.py" @@ -0,0 +1,60 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + one = 0 + zero = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == '1': one += 1 + else: zero += 1 + + if one==A: return '1' + elif zero==A: return '0' + else: return '-1' + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +def quad(arr): + result = "" + status = conquer(arr) + + if status == '0': result += "0" + elif status == '1': result += "1" + else: + result += "(" + dividearr = divide(arr) + for da in dividearr: + result += quad(da) + result += ")" + return result + +N = int(sys.stdin.readline()) + +video = [] + +for i in range(N): + value = sys.stdin.readline() + video.append(value) + +sys.stdout.write(quad(video)) \ No newline at end of file diff --git "a/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" new file mode 100644 index 0000000..77dbb1e --- /dev/null +++ "b/src/Do-ho/divide_conquer/boj_2630_\354\203\211\354\242\205\354\235\264\353\247\214\353\223\244\352\270\260/boj_2630.py" @@ -0,0 +1,59 @@ +import sys +from collections import deque + +def conquer(arr): + L = len(arr) + A = L * L + white = 0 + blue = 0 + + if A==1: return arr[0][0] + + for i in range(L): + for j in range(L): + if arr[i][j] == 0: white += 1 + else: blue += 1 + + if white==A: return 0 + elif blue==A: return 1 + else: return -1 + +def divide(arr): + L = len(arr) + + area1 = deque() + area2 = deque() + area3 = deque() + area4 = deque() + + for i in range(0, int(L/2)): + area1.append(arr[i][:int(L/2)]) + area2.append(arr[i][int(L/2):]) + for i in range(int(L/2), L): + area3.append(arr[i][:int(L/2)]) + area4.append(arr[i][int(L/2):]) + + return [area1, area2, area3, area4] + +N = int(sys.stdin.readline()) + +paper = [] +white_paper = 0 +blue_paper = 0 + +for i in range(N): + paper.append(list(map(int, sys.stdin.readline().split()))) + +queue = deque() +queue.append(paper) + +while queue: + target = queue.popleft() + status = conquer(target) + if status == 0: white_paper +=1 + elif status == 1: blue_paper += 1 + else: + queue.extend(divide(target)) + +print(white_paper) +print(blue_paper) \ No newline at end of file From 3cd384db4b04e4a8e01fe97532d30030d359f6f6 Mon Sep 17 00:00:00 2001 From: doreen <50297117+do02reen24@users.noreply.github.com> Date: Sun, 18 Oct 2020 20:53:31 +0900 Subject: [PATCH 069/193] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 8주차 문제 업로드 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 6f35bdb..1d02545 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ | 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | | 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | | 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | +| 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | ## :blue_book: Additional Study From 0d5ad9aca44efa68a9ec9e5dac45cfa2295cb797 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 18 Oct 2020 21:51:23 +0900 Subject: [PATCH 070/193] solve : baekjoon 1094 --- src/do02reen24/Review/week7.md | 12 ++++++++++++ src/do02reen24/bit-masking/baekjoon_1094.py | 13 +++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/do02reen24/Review/week7.md create mode 100644 src/do02reen24/bit-masking/baekjoon_1094.py diff --git a/src/do02reen24/Review/week7.md b/src/do02reen24/Review/week7.md new file mode 100644 index 0000000..3d9b96a --- /dev/null +++ b/src/do02reen24/Review/week7.md @@ -0,0 +1,12 @@ +# :fire: week6 + +## :ballot_box_with_check: 백준 1094 + +* list를 사용하지 않고 풀고 싶었는데 잘안돼서 그냥 list로 풀었다. + +## :ballot_box_with_check: 백준 14889 + +## :ballot_box_with_check: 백준 18233 + +## :ballot_box_with_check: 백준 1194 + diff --git a/src/do02reen24/bit-masking/baekjoon_1094.py b/src/do02reen24/bit-masking/baekjoon_1094.py new file mode 100644 index 0000000..b682520 --- /dev/null +++ b/src/do02reen24/bit-masking/baekjoon_1094.py @@ -0,0 +1,13 @@ +import sys + +if __name__ == '__main__': + x = int(sys.stdin.readline()) + stick = [64] + stick_sum = 64 + while not x == stick_sum: + half_stick = int(stick.pop() / 2) + stick.append(half_stick) + stick_sum = sum(stick) + if stick_sum < x: + stick.append(half_stick) + print(len(stick)) From 1f73ba1cdb554c0f5a946a03eca54c26729193f2 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 18 Oct 2020 22:39:59 +0900 Subject: [PATCH 071/193] solve : baekjoon 14889 --- src/do02reen24/Review/week7.md | 2 ++ src/do02reen24/bit-masking/baekjoon_14889.cpp | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/do02reen24/bit-masking/baekjoon_14889.cpp diff --git a/src/do02reen24/Review/week7.md b/src/do02reen24/Review/week7.md index 3d9b96a..c0a12e3 100644 --- a/src/do02reen24/Review/week7.md +++ b/src/do02reen24/Review/week7.md @@ -6,6 +6,8 @@ ## :ballot_box_with_check: 백준 14889 +* c++의 permutation을 쓰면 쉬울 것 같아 c++로 해결하였다. + ## :ballot_box_with_check: 백준 18233 ## :ballot_box_with_check: 백준 1194 diff --git a/src/do02reen24/bit-masking/baekjoon_14889.cpp b/src/do02reen24/bit-masking/baekjoon_14889.cpp new file mode 100644 index 0000000..bb93544 --- /dev/null +++ b/src/do02reen24/bit-masking/baekjoon_14889.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; +const int MAX_INT = 20; +int main() { + int n; + int ans = -1; + vector order; + int team[MAX_INT][MAX_INT]; + cin >> n; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) cin >> team[j][i]; + if (i < (n / 2)) order.push_back(0); + else order.push_back(1); + } + + do { + int start = 0; + int link = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (i == j) continue; + if (order[i] == 0 && order[j] == 0) start += team[i][j] + team[j][i]; + if(order[i] == 1 && order[j] == 1) link += team[i][j] + team[j][i]; + } + } + int diff = abs(start - link) / 2; + if (ans == -1 || ans > diff) ans = diff; + } while (next_permutation(order.begin(), order.end())); + + cout << ans << endl; +} \ No newline at end of file From 62e0139f6c124570c9de1ae9e4f64806c29a32fb Mon Sep 17 00:00:00 2001 From: Do-ho Date: Mon, 19 Oct 2020 05:06:21 +0900 Subject: [PATCH 072/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20109?= =?UTF-8?q?4=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 비트 조작을 통한 풀이 --- .../boj_1094.py" | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" diff --git "a/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" new file mode 100644 index 0000000..d3a2099 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" @@ -0,0 +1,10 @@ +import sys + +X = int(sys.stdin.readline()) + +count = 0 +while(X!=0): + if X%2==1: count += 1 + X = X >> 1 + +sys.stdout.write(str(count)) \ No newline at end of file From 8967a24cbb0ac8e0d6dba9c0a13b66fa561a2a9b Mon Sep 17 00:00:00 2001 From: Do-ho Date: Mon, 19 Oct 2020 05:06:41 +0900 Subject: [PATCH 073/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20148?= =?UTF-8?q?89=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 비트마스킹을 통한 풀이 --- .../boj_14889.py" | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" diff --git "a/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" new file mode 100644 index 0000000..4dd4fa1 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" @@ -0,0 +1,43 @@ +import sys +from itertools import combinations + +def getTeamStats(comb): + startTeamStat = getStat(comb) + + linkTeam = [] + for people in peoples: + if people not in comb: + linkTeam.append(people) + + linkTeamStat = getStat(linkTeam) + + return [startTeamStat, linkTeamStat] + +def getStat(peoples): + result = 0 + for item1 in peoples: + for item2 in peoples: + if item1==item2: continue + result += stats[item1][item2] + + return result + +N = int(sys.stdin.readline()) +halfN = N//2 +stats = [] +peoples = [i for i in range(N)] +team_combinations = [] +balanceStat = 10000 + +for _ in range(N): + stats.append(list(map(int, sys.stdin.readline().split()))) + +for team in list(combinations(peoples, halfN)): + team_combinations.append(team) + +for comb in team_combinations: + [startTeamStat, linkTeamStat] = getTeamStats(comb) + if balanceStat > abs(startTeamStat - linkTeamStat): + balanceStat = abs(startTeamStat - linkTeamStat) + +sys.stdout.write(str(balanceStat)) \ No newline at end of file From 5b7d20e8eace5d6772f72f7ebf81f10d688972c2 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Mon, 19 Oct 2020 05:06:50 +0900 Subject: [PATCH 074/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20182?= =?UTF-8?q?33=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 비트마스킹을 통한 풀이 --- .../boj_18233.py" | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" diff --git "a/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" new file mode 100644 index 0000000..2204e17 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" @@ -0,0 +1,47 @@ +import sys +from itertools import combinations + +[N, P, E] = map(int, sys.stdin.readline().split()) + +peoples = [i for i in range(N)] + +combs = [] +for comb in list(combinations(peoples, P)): + combs.append(comb) + +peopleDolls = [] +for _ in range(N): + data = sys.stdin.readline().split() + peopleDolls.append({'min': int(data[0]), 'max': int(data[1])}) + +def f(): + global combs + for comb in combs: + result = [0 for _ in range(N)] + total = 0 + for i in comb: + total += peopleDolls[i]['min'] + result[i] = peopleDolls[i]['min'] + + if total>E: continue + elif total==E: return result + + # E-total은 남은 인형 개수 + for i in comb: + remainTotalDoll = E - total + remainCombDoll = peopleDolls[i]['max'] - peopleDolls[i]['min'] + + if remainTotalDoll >= remainCombDoll: + result[i] += remainCombDoll + total += remainCombDoll + remainTotalDoll -= remainCombDoll + else: + result[i] += remainTotalDoll + total += remainTotalDoll + remainTotalDoll = 0 + + if remainTotalDoll==0: return result + return [-1] + +for i in f(): + sys.stdout.write(str(i) + ' ') \ No newline at end of file From 1605d8a4a1cd364558af7ca9eedf6296d0a0649f Mon Sep 17 00:00:00 2001 From: Do-ho Date: Mon, 19 Oct 2020 05:07:03 +0900 Subject: [PATCH 075/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20119?= =?UTF-8?q?4=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 --- .../boj_1194.py" | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" diff --git "a/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" new file mode 100644 index 0000000..f008a5d --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" @@ -0,0 +1,54 @@ +import sys +import copy +from itertools import combinations +from collections import deque + +[N, M] = list(map(int, sys.stdin.readline().split())) +directions = [(-1, 0), (0, -1), (1, 0), (0, 1)] +alphabet = { + 'A': 0, + 'B': 1, + 'C': 2, + 'D': 3, + 'E': 4, + 'F': 5 +} + +myMap = [] +myCheck = [[[False for _ in range(64)] for _ in range(M)] for _ in range(N)] + +for _ in range(N): + myMap.append(list(sys.stdin.readline()[:-1])) + +# 맵 중 민식이 위치 찾기 (민식이는 무조건 있다) +def findMinsik(): + for i in range(len(myMap)): + for j in range(len(myMap[0])): + if myMap[i][j]=='0': + return (i, j, 0, 0) + +def findMoon(): + queue = deque() + queue.append(findMinsik()) + myCheck[queue[0][0]][queue[0][1]][0] = True + while queue: + target = queue.popleft() + for direction in directions: + nr = target[0] + direction[0] + nc = target[1] + direction[1] + nk = copy.deepcopy(target[2]) + + if nr >= N or nr < 0 or nc >= M or nc < 0: continue + if myMap[nr][nc] == '1': return target[3] + 1 + if myMap[nr][nc] == '#' or myCheck[nr][nc][nk]: continue + if myMap[nr][nc].isupper(): + if nk == 0 or (nk >> alphabet[myMap[nr][nc]]) % 2 != 1: continue + if myMap[nr][nc].islower(): + uA = myMap[nr][nc].upper() + if nk == 0 or (nk >> alphabet[uA]) % 2 != 1: nk += pow(2,alphabet[uA]) + + myCheck[nr][nc][nk] = True + queue.append((nr, nc, nk, target[3]+1)) + return -1 + +print(findMoon()) \ No newline at end of file From 5838d456b6b241b402dbd8c6f576b75c44eb13fc Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Mon, 19 Oct 2020 11:30:00 +0900 Subject: [PATCH 076/193] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1d02545..938e7a7 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ | 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | | 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | | 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | +| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평볌한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | | ## :blue_book: Additional Study From 608864509a311f7db2235946d55cd6ab48d31300 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Mon, 19 Oct 2020 11:37:31 +0900 Subject: [PATCH 077/193] Add: Upload week7 code and readme file --- src/grap3fruit/boj/1094.md | 11 +++++ src/grap3fruit/boj/1094.py | 26 +++++++++++ src/grap3fruit/boj/14889.md | 24 +++++++++++ src/grap3fruit/boj/14889.py | 65 ++++++++++++++++++++++++++++ src/grap3fruit/boj/18233.md | 21 +++++++++ src/grap3fruit/boj/18233.py | 86 +++++++++++++++++++++++++++++++++++++ 6 files changed, 233 insertions(+) create mode 100644 src/grap3fruit/boj/1094.md create mode 100644 src/grap3fruit/boj/1094.py create mode 100644 src/grap3fruit/boj/14889.md create mode 100644 src/grap3fruit/boj/14889.py create mode 100644 src/grap3fruit/boj/18233.md create mode 100644 src/grap3fruit/boj/18233.py diff --git a/src/grap3fruit/boj/1094.md b/src/grap3fruit/boj/1094.md new file mode 100644 index 0000000..b364969 --- /dev/null +++ b/src/grap3fruit/boj/1094.md @@ -0,0 +1,11 @@ +# 1094 - 성공 + +## 비트마스크 + +- 문제 내용대로 풀면 됨 +- 일단 current_min을 지우고, 절반을 통해 계산을 하고, +- 1-2번 조건까지 가게 되면 그때 절반을 추가해준다. + +## 보완 + +- 비트마스크를 활용하지 않았는데, 활용해보면 좋을듯. diff --git a/src/grap3fruit/boj/1094.py b/src/grap3fruit/boj/1094.py new file mode 100644 index 0000000..67dd6f5 --- /dev/null +++ b/src/grap3fruit/boj/1094.py @@ -0,0 +1,26 @@ +import sys + +target = int(sys.stdin.readline()) + +datas = [64] + +def calc(datas): + if sum(datas) > target: + current_min = min(datas) + datas.remove(current_min) + datas.append(current_min/2) + + if sum(datas) == target: + return len(datas) + + if sum(datas) > target: + return calc(datas) + + if sum(datas) < target: + datas.append(current_min/2) + return calc(datas) + + if sum(datas) == target: + return len(datas) + +print(calc(datas)) \ No newline at end of file diff --git a/src/grap3fruit/boj/14889.md b/src/grap3fruit/boj/14889.md new file mode 100644 index 0000000..83cfb3e --- /dev/null +++ b/src/grap3fruit/boj/14889.md @@ -0,0 +1,24 @@ +# 14889 - 성공 + +## 브루트포스 + +- 전체 케이스 구하는 함수 +- 사람 a,b 능력치 합 구하는 함수 +- 팀내 능력치 합 구하는 함수 +- 콤비네이션 써서 구현함 + +## pseudocode + +``` +cases = get_cases를 통해 팀A와 팀B로 나눌 경우의수 + +calc 함수 + 전체 case를 돌면서 + 팀A와 팀B의 능력치 합을 각각 구해서 + 둘의 차이를 비교하고 + 최소값을 리턴. +``` + +## 보완 + +- 도연님 사용하신 next_permutation도 유용해 보인다 diff --git a/src/grap3fruit/boj/14889.py b/src/grap3fruit/boj/14889.py new file mode 100644 index 0000000..7eed3b2 --- /dev/null +++ b/src/grap3fruit/boj/14889.py @@ -0,0 +1,65 @@ +import sys +from itertools import combinations + +n = int(sys.stdin.readline()) +arr = [] + +for i in range(0,n): + arr.append(list(map(int,sys.stdin.readline().strip().split()))) +# n = 6 + +cases = [] +for i in range(1,n+1): + cases.append(i) + +# 전체 케이스 구하는 함수 +def get_cases(n, cases): + combination_cases = list(combinations(cases,int(n/2))) + teamA_cases = [] + + for case in combination_cases: + if case[0] == 1 : + teamA_cases.append(case) + + result = [] + for teamA in teamA_cases: + teamB = (set(cases) - set(teamA)) + result.append([set(teamA), teamB]) + + return result + +cases = get_cases(n, cases) +print(cases) + +# 사람 a,b 능력치 합 +def get_sum(a,b,arr): + return arr[a-1][b-1] + arr[b-1][a-1] + +# print(get_sum(4,6,arr)) + +# 팀내 능력치 합 구하는 함수 +def get_team_sum(team, arr): + sum = 0 + for members in list(combinations(team,2)): + # print(members) + sum += get_sum(members[0], members[1], arr) + + return sum + +# print(get_team_sum({1,2,3}, arr)) + +def calc(cases, arr): + min = 1000 + + for case in cases: + teamA_sum = get_team_sum(case[0], arr) + teamB_sum = get_team_sum(case[1], arr) + + current_min = abs(teamA_sum - teamB_sum) + # print(case, current_min) + if current_min < min : + min = current_min + + return min + +print(calc(cases, arr)) \ No newline at end of file diff --git a/src/grap3fruit/boj/18233.md b/src/grap3fruit/boj/18233.md new file mode 100644 index 0000000..1e49115 --- /dev/null +++ b/src/grap3fruit/boj/18233.md @@ -0,0 +1,21 @@ +# 18233 - 시간초과 + +## 비트마스크 + +## pseudocode + +``` +입력받을때, + Min이 E초과일때는 넘김. + Max가 E초과일때는 MAX를 E로 함. + +조합 경우의수는 콤비네이션을 P만큼 해서 구함. + +위에서 구해진 가능한 조합을 돌면서, + 해당 조합에서 가능한 합들을 모두 구하고, + 그 합들 중에 E가 있으면 정답을 리턴함. +``` + +## 보완 + +- 도연님, 도호님 하신것 처럼 min max 값 활용하여 해야할듯. 모든 case를 다 펴서 하는건 시간초과 뜰수밖에 읍다.. diff --git a/src/grap3fruit/boj/18233.py b/src/grap3fruit/boj/18233.py new file mode 100644 index 0000000..ebd6362 --- /dev/null +++ b/src/grap3fruit/boj/18233.py @@ -0,0 +1,86 @@ +import sys +from itertools import combinations +import copy + +N, P, E = list(map(int,sys.stdin.readline().strip().split())) + +members = [] +for i in range(0,N): + min, max = list(map(int,sys.stdin.readline().strip().split())) + temp_set = set([]) + + if min > E: + continue + + if max > E: + max = E + + for i in range(min,max+1): + temp_set.add(i) + members.append(temp_set) + +print(members) + +cases = [] +for i in range(0,len(members)): + cases.append(i) + +combination_cases = list(combinations(cases,P)) + +print(combination_cases) + +# n중 포문 생성. +def iter_func(case, count): + if count == 0: #가장 깊은 스택 + sum_dic = dict() + for i in members[case[len(case)-count-1]]: + sum_dic[i] = [i] + return sum_dic + + sum_dic = iter_func(case, count-1) + + temp_dic = copy.deepcopy(sum_dic) + for i in members[case[len(case)-count-1]]: + for key, value in sum_dic.items(): + try: + if len(temp_dic[i+key]) == len(case): #이미 해당 key가 차있으면 넘어감 + continue + if sum(temp_dic[i+key]+i) == i+key: + temp_dic[i+key].append(i) + except: + newlist = list(value) + newlist.append(i) + temp_dic[i+key] = newlist + + if i+key == E and len(temp_dic[i+key]) == len(case): #현재 i+key 키가 E와 같고, 차있으면 바로 리턴. + return temp_dic + # print(temp_dic) + + return temp_dic + +def getResult(case, value): + result = [] + for i in range(0,N): + result.append(0) + + for i in range(0,len(case)): + result[case[i]] = value[len(case)-i-1] + + return result + +flag = False +for case in combination_cases: + case_dic = iter_func(case, len(case)-1) + # print(case_dic) + if E in case_dic.keys(): + if len(case_dic[E]) == len(case) : + print(case) + print(case_dic[E]) + flag = True + + print(getResult(case, case_dic[E])) + # break + +if flag == False: + print(-1) + From ca8d81f91b78e4088938ef77d2442920885275f5 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 19 Oct 2020 12:28:21 +0900 Subject: [PATCH 078/193] unsolved : baekjoon 18233 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 86%에서 틀림 --- src/do02reen24/Review/week7.md | 55 ++++++++++++++++++- src/do02reen24/bit-masking/baekjoon_18233.cpp | 46 ++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 src/do02reen24/bit-masking/baekjoon_18233.cpp diff --git a/src/do02reen24/Review/week7.md b/src/do02reen24/Review/week7.md index c0a12e3..881dedc 100644 --- a/src/do02reen24/Review/week7.md +++ b/src/do02reen24/Review/week7.md @@ -1,14 +1,67 @@ -# :fire: week6 +# :fire: week7 ## :ballot_box_with_check: 백준 1094 * list를 사용하지 않고 풀고 싶었는데 잘안돼서 그냥 list로 풀었다. +* 스터디 고찰: 비트마스크를 써서 풀면 코드가 훨씬 간결함을 알게 되었다. ## :ballot_box_with_check: 백준 14889 * c++의 permutation을 쓰면 쉬울 것 같아 c++로 해결하였다. +* 스터디 고찰 : python의 경우 combination을 써서 풀 수 있음을 알게 되었다. ## :ballot_box_with_check: 백준 18233 +#### 틀렸습니다. (86%) + +```c++ +#include +#include +#include +using namespace std; + +int main() { + int n, p, e; + cin >> n >> p >> e; + vector> member; + vector isGift(n); + for (int i = 0; i < n; i++) { + int min, max; + cin >> min >> max; + member.push_back(make_pair(min, max)); + if ((n - i) <= p) isGift[i] = 1; + } + do { + int min = 0, max = 0; + int sol[20] = { 0, }; + for (int i = 0; i < n; i++) { + if (isGift[i] == 0) continue; + min += member[i].first; + max += member[i].second; + sol[i] = member[i].first; + } + int remain = e - min; + if (min <= e && max >= e) { + for (int i = 0; i < n; i++) { + if (isGift[i] == 0) continue; + int diff = member[i].second - member[i].first; + if (diff < remain) { + remain -= diff; + sol[i] += diff; + } + else { + sol[i] += remain; + break; + } + } + for (int i = 0; i < n; i++) cout << sol[i] << " "; + return 0; + } + } while (next_permutation(isGift.begin(), isGift.end())); + cout << -1 << endl; + return 0; +} +``` + ## :ballot_box_with_check: 백준 1194 diff --git a/src/do02reen24/bit-masking/baekjoon_18233.cpp b/src/do02reen24/bit-masking/baekjoon_18233.cpp new file mode 100644 index 0000000..a767379 --- /dev/null +++ b/src/do02reen24/bit-masking/baekjoon_18233.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +using namespace std; + +int main() { + int n, p, e; + cin >> n >> p >> e; + vector> member; + vector isGift(n); + for (int i = 0; i < n; i++) { + int min, max; + cin >> min >> max; + member.push_back(make_pair(min, max)); + if ((n - i) <= p) isGift[i] = 1; + } + do { + int min = 0, max = 0; + int sol[20] = { 0, }; + for (int i = 0; i < n; i++) { + if (isGift[i] == 0) continue; + min += member[i].first; + max += member[i].second; + sol[i] = member[i].first; + } + int remain = e - min; + if (min <= e && max >= e) { + for (int i = 0; i < n; i++) { + if (isGift[i] == 0) continue; + int diff = member[i].second - member[i].first; + if (diff < remain) { + remain -= diff; + sol[i] += diff; + } + else { + sol[i] += remain; + remain = 0; + } + } + for (int i = 0; i < n; i++) cout << sol[i] << " "; + return 0; + } + } while (next_permutation(isGift.begin(), isGift.end())); + cout << -1 << endl; + return 0; +} \ No newline at end of file From 76a1def26288f36f83ff5d2a56f7f9deecab4249 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Mon, 19 Oct 2020 17:14:23 +0900 Subject: [PATCH 079/193] =?UTF-8?q?[WEEK7]=20=EB=B9=84=ED=8A=B8=EB=A7=88?= =?UTF-8?q?=EC=8A=A4=ED=82=B9=20(#19)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1094 문제 - 비트 조작을 통한 풀이 * Add: solve 백준 14889 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 18233 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 1194 문제 - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 --- .../boj_1094.py" | 10 ++++ .../boj_1194.py" | 54 +++++++++++++++++++ .../boj_14889.py" | 43 +++++++++++++++ .../boj_18233.py" | 47 ++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" create mode 100644 "src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" create mode 100644 "src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" create mode 100644 "src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" diff --git "a/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" new file mode 100644 index 0000000..d3a2099 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" @@ -0,0 +1,10 @@ +import sys + +X = int(sys.stdin.readline()) + +count = 0 +while(X!=0): + if X%2==1: count += 1 + X = X >> 1 + +sys.stdout.write(str(count)) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" new file mode 100644 index 0000000..f008a5d --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" @@ -0,0 +1,54 @@ +import sys +import copy +from itertools import combinations +from collections import deque + +[N, M] = list(map(int, sys.stdin.readline().split())) +directions = [(-1, 0), (0, -1), (1, 0), (0, 1)] +alphabet = { + 'A': 0, + 'B': 1, + 'C': 2, + 'D': 3, + 'E': 4, + 'F': 5 +} + +myMap = [] +myCheck = [[[False for _ in range(64)] for _ in range(M)] for _ in range(N)] + +for _ in range(N): + myMap.append(list(sys.stdin.readline()[:-1])) + +# 맵 중 민식이 위치 찾기 (민식이는 무조건 있다) +def findMinsik(): + for i in range(len(myMap)): + for j in range(len(myMap[0])): + if myMap[i][j]=='0': + return (i, j, 0, 0) + +def findMoon(): + queue = deque() + queue.append(findMinsik()) + myCheck[queue[0][0]][queue[0][1]][0] = True + while queue: + target = queue.popleft() + for direction in directions: + nr = target[0] + direction[0] + nc = target[1] + direction[1] + nk = copy.deepcopy(target[2]) + + if nr >= N or nr < 0 or nc >= M or nc < 0: continue + if myMap[nr][nc] == '1': return target[3] + 1 + if myMap[nr][nc] == '#' or myCheck[nr][nc][nk]: continue + if myMap[nr][nc].isupper(): + if nk == 0 or (nk >> alphabet[myMap[nr][nc]]) % 2 != 1: continue + if myMap[nr][nc].islower(): + uA = myMap[nr][nc].upper() + if nk == 0 or (nk >> alphabet[uA]) % 2 != 1: nk += pow(2,alphabet[uA]) + + myCheck[nr][nc][nk] = True + queue.append((nr, nc, nk, target[3]+1)) + return -1 + +print(findMoon()) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" new file mode 100644 index 0000000..4dd4fa1 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" @@ -0,0 +1,43 @@ +import sys +from itertools import combinations + +def getTeamStats(comb): + startTeamStat = getStat(comb) + + linkTeam = [] + for people in peoples: + if people not in comb: + linkTeam.append(people) + + linkTeamStat = getStat(linkTeam) + + return [startTeamStat, linkTeamStat] + +def getStat(peoples): + result = 0 + for item1 in peoples: + for item2 in peoples: + if item1==item2: continue + result += stats[item1][item2] + + return result + +N = int(sys.stdin.readline()) +halfN = N//2 +stats = [] +peoples = [i for i in range(N)] +team_combinations = [] +balanceStat = 10000 + +for _ in range(N): + stats.append(list(map(int, sys.stdin.readline().split()))) + +for team in list(combinations(peoples, halfN)): + team_combinations.append(team) + +for comb in team_combinations: + [startTeamStat, linkTeamStat] = getTeamStats(comb) + if balanceStat > abs(startTeamStat - linkTeamStat): + balanceStat = abs(startTeamStat - linkTeamStat) + +sys.stdout.write(str(balanceStat)) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" new file mode 100644 index 0000000..2204e17 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" @@ -0,0 +1,47 @@ +import sys +from itertools import combinations + +[N, P, E] = map(int, sys.stdin.readline().split()) + +peoples = [i for i in range(N)] + +combs = [] +for comb in list(combinations(peoples, P)): + combs.append(comb) + +peopleDolls = [] +for _ in range(N): + data = sys.stdin.readline().split() + peopleDolls.append({'min': int(data[0]), 'max': int(data[1])}) + +def f(): + global combs + for comb in combs: + result = [0 for _ in range(N)] + total = 0 + for i in comb: + total += peopleDolls[i]['min'] + result[i] = peopleDolls[i]['min'] + + if total>E: continue + elif total==E: return result + + # E-total은 남은 인형 개수 + for i in comb: + remainTotalDoll = E - total + remainCombDoll = peopleDolls[i]['max'] - peopleDolls[i]['min'] + + if remainTotalDoll >= remainCombDoll: + result[i] += remainCombDoll + total += remainCombDoll + remainTotalDoll -= remainCombDoll + else: + result[i] += remainTotalDoll + total += remainTotalDoll + remainTotalDoll = 0 + + if remainTotalDoll==0: return result + return [-1] + +for i in f(): + sys.stdout.write(str(i) + ' ') \ No newline at end of file From 369e01541f63c20c779aa0ff1e2fb7c3685e1e39 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Mon, 19 Oct 2020 17:14:43 +0900 Subject: [PATCH 080/193] Do ho (#22) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [week6] 분할정복법 (#17) * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * [WEEK7] 비트마스킹 (#19) * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1094 문제 - 비트 조작을 통한 풀이 * Add: solve 백준 14889 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 18233 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 1194 문제 - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 --- .../boj_1094.py" | 10 ++++ .../boj_1194.py" | 54 +++++++++++++++++++ .../boj_14889.py" | 43 +++++++++++++++ .../boj_18233.py" | 47 ++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 "src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" create mode 100644 "src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" create mode 100644 "src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" create mode 100644 "src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" diff --git "a/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" new file mode 100644 index 0000000..d3a2099 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1094_\353\247\211\353\214\200\352\270\260/boj_1094.py" @@ -0,0 +1,10 @@ +import sys + +X = int(sys.stdin.readline()) + +count = 0 +while(X!=0): + if X%2==1: count += 1 + X = X >> 1 + +sys.stdout.write(str(count)) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" new file mode 100644 index 0000000..f008a5d --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244/boj_1194.py" @@ -0,0 +1,54 @@ +import sys +import copy +from itertools import combinations +from collections import deque + +[N, M] = list(map(int, sys.stdin.readline().split())) +directions = [(-1, 0), (0, -1), (1, 0), (0, 1)] +alphabet = { + 'A': 0, + 'B': 1, + 'C': 2, + 'D': 3, + 'E': 4, + 'F': 5 +} + +myMap = [] +myCheck = [[[False for _ in range(64)] for _ in range(M)] for _ in range(N)] + +for _ in range(N): + myMap.append(list(sys.stdin.readline()[:-1])) + +# 맵 중 민식이 위치 찾기 (민식이는 무조건 있다) +def findMinsik(): + for i in range(len(myMap)): + for j in range(len(myMap[0])): + if myMap[i][j]=='0': + return (i, j, 0, 0) + +def findMoon(): + queue = deque() + queue.append(findMinsik()) + myCheck[queue[0][0]][queue[0][1]][0] = True + while queue: + target = queue.popleft() + for direction in directions: + nr = target[0] + direction[0] + nc = target[1] + direction[1] + nk = copy.deepcopy(target[2]) + + if nr >= N or nr < 0 or nc >= M or nc < 0: continue + if myMap[nr][nc] == '1': return target[3] + 1 + if myMap[nr][nc] == '#' or myCheck[nr][nc][nk]: continue + if myMap[nr][nc].isupper(): + if nk == 0 or (nk >> alphabet[myMap[nr][nc]]) % 2 != 1: continue + if myMap[nr][nc].islower(): + uA = myMap[nr][nc].upper() + if nk == 0 or (nk >> alphabet[uA]) % 2 != 1: nk += pow(2,alphabet[uA]) + + myCheck[nr][nc][nk] = True + queue.append((nr, nc, nk, target[3]+1)) + return -1 + +print(findMoon()) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" new file mode 100644 index 0000000..4dd4fa1 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254/boj_14889.py" @@ -0,0 +1,43 @@ +import sys +from itertools import combinations + +def getTeamStats(comb): + startTeamStat = getStat(comb) + + linkTeam = [] + for people in peoples: + if people not in comb: + linkTeam.append(people) + + linkTeamStat = getStat(linkTeam) + + return [startTeamStat, linkTeamStat] + +def getStat(peoples): + result = 0 + for item1 in peoples: + for item2 in peoples: + if item1==item2: continue + result += stats[item1][item2] + + return result + +N = int(sys.stdin.readline()) +halfN = N//2 +stats = [] +peoples = [i for i in range(N)] +team_combinations = [] +balanceStat = 10000 + +for _ in range(N): + stats.append(list(map(int, sys.stdin.readline().split()))) + +for team in list(combinations(peoples, halfN)): + team_combinations.append(team) + +for comb in team_combinations: + [startTeamStat, linkTeamStat] = getTeamStats(comb) + if balanceStat > abs(startTeamStat - linkTeamStat): + balanceStat = abs(startTeamStat - linkTeamStat) + +sys.stdout.write(str(balanceStat)) \ No newline at end of file diff --git "a/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" new file mode 100644 index 0000000..2204e17 --- /dev/null +++ "b/src/Do-ho/bitmasking/boj_18233_\353\237\254\353\262\204\353\215\225/boj_18233.py" @@ -0,0 +1,47 @@ +import sys +from itertools import combinations + +[N, P, E] = map(int, sys.stdin.readline().split()) + +peoples = [i for i in range(N)] + +combs = [] +for comb in list(combinations(peoples, P)): + combs.append(comb) + +peopleDolls = [] +for _ in range(N): + data = sys.stdin.readline().split() + peopleDolls.append({'min': int(data[0]), 'max': int(data[1])}) + +def f(): + global combs + for comb in combs: + result = [0 for _ in range(N)] + total = 0 + for i in comb: + total += peopleDolls[i]['min'] + result[i] = peopleDolls[i]['min'] + + if total>E: continue + elif total==E: return result + + # E-total은 남은 인형 개수 + for i in comb: + remainTotalDoll = E - total + remainCombDoll = peopleDolls[i]['max'] - peopleDolls[i]['min'] + + if remainTotalDoll >= remainCombDoll: + result[i] += remainCombDoll + total += remainCombDoll + remainTotalDoll -= remainCombDoll + else: + result[i] += remainTotalDoll + total += remainTotalDoll + remainTotalDoll = 0 + + if remainTotalDoll==0: return result + return [-1] + +for i in f(): + sys.stdout.write(str(i) + ' ') \ No newline at end of file From 7313bbab75cf585ba2caffb580f3af8fed4428ea Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 22 Oct 2020 21:47:23 +0900 Subject: [PATCH 081/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20110?= =?UTF-8?q?47=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 그리디 알고리즘을 통한 풀이 --- .../README.md" | 64 +++++++++++++++++++ .../boj_11047.py" | 29 +++++++++ 2 files changed, 93 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" new file mode 100644 index 0000000..009dbe1 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" @@ -0,0 +1,64 @@ +# 동전 0 + +- 1번 째 시도 (시간 초과) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + for coinKind in coinKinds: + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + K = mindiff + count += 1 + +print(count) +``` + +- 2번째 시도 (한번에 처리) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) +``` \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" new file mode 100644 index 0000000..04d5026 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" @@ -0,0 +1,29 @@ +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) \ No newline at end of file From 80f642c19132967874f6d4e97ecc7f433729cea6 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 22 Oct 2020 21:47:35 +0900 Subject: [PATCH 082/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20114?= =?UTF-8?q?97=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 그리디 알고리즘을 통한 풀이 --- .../boj_11497.py" | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" diff --git "a/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" new file mode 100644 index 0000000..f01ed09 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" @@ -0,0 +1,27 @@ +import sys +from collections import deque + +def diff(a, b): + return abs(a-b) + +T = int(sys.stdin.readline()) + +for _ in range(T): + N = int(sys.stdin.readline()) + tongtree = list(map(int, sys.stdin.readline().split())) + newtongtree = deque() + tongtree.sort() + + for item in tongtree: + topIdx = len(newtongtree) + if topIdx <= 1: newtongtree.append(item) + else: + if newtongtree[0] > newtongtree[topIdx-1]: newtongtree.append(item) + else: newtongtree.appendleft(item) + + maxDiff = diff(newtongtree[0], newtongtree[1]) + for idx in range(N-1): + value = diff(newtongtree[idx], newtongtree[idx+1]) + if maxDiff < value: maxDiff = value + + print(maxDiff) \ No newline at end of file From 75f53c1c1bcf426ccb188735ca702be338413e7b Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 22 Oct 2020 21:47:42 +0900 Subject: [PATCH 083/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20194?= =?UTF-8?q?6=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 그리디 알고리즘을 통한 풀이 --- .../boj_1946.py" | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" diff --git "a/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" new file mode 100644 index 0000000..2b9ec08 --- /dev/null +++ "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" @@ -0,0 +1,18 @@ +import sys + +T = int(sys.stdin.readline()) + +for _ in range(T): + employees = [] + N = int(sys.stdin.readline()) + for _ in range(N): + employees.append(list(map(int, sys.stdin.readline().split()))) + employees.sort() + + testEmployee = employees[0] + count = 1 + for employee in employees: + if testEmployee[1] > employee[1]: + count += 1 + testEmployee = employee + print(count) \ No newline at end of file From a2abcdd430d0231c6f843224326c86dfcf93daa9 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 22 Oct 2020 22:18:17 +0900 Subject: [PATCH 084/193] solve : baekjoon 1946 --- src/do02reen24/Review/week8.md | 12 ++++++++++++ src/do02reen24/greedy/baekjoon_1946.py | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/do02reen24/Review/week8.md create mode 100644 src/do02reen24/greedy/baekjoon_1946.py diff --git a/src/do02reen24/Review/week8.md b/src/do02reen24/Review/week8.md new file mode 100644 index 0000000..8ac2f61 --- /dev/null +++ b/src/do02reen24/Review/week8.md @@ -0,0 +1,12 @@ +# :fire: week8 + +## :ballot_box_with_check: 백준 1946 + +- 문제 이해를 하는데 시간이 좀 오래 걸렸다. +- 정렬을 이용하면 간단하게 풀 수 있다. + +## :ballot_box_with_check: 백준 11047 + +## :ballot_box_with_check: 백준 11497 + +## :ballot_box_with_check: 백준 2504 diff --git a/src/do02reen24/greedy/baekjoon_1946.py b/src/do02reen24/greedy/baekjoon_1946.py new file mode 100644 index 0000000..4d93037 --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_1946.py @@ -0,0 +1,19 @@ +import sys + +if __name__ == "__main__": + T = int(sys.stdin.readline()) + for _ in range(T): + n = int(sys.stdin.readline()) + applicant = [] + for i in range(n): + rankA, rankB = map(int, sys.stdin.readline().split(' ')) + applicant.append([rankA, rankB]) + applicant.sort(key = lambda rank: rank[0]) + + minB = applicant[0][1] + ans = 0 + for rankA, rankB in applicant: + if rankB <= minB: + minB = rankB + ans += 1 + print(ans) \ No newline at end of file From dfd6e05f4a460e81b196e45e5cea6da32c90a08c Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 22 Oct 2020 22:25:52 +0900 Subject: [PATCH 085/193] solve : baekjoon 11047 --- src/do02reen24/Review/week8.md | 2 ++ src/do02reen24/greedy/baekjoon_11047.py | 14 ++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/do02reen24/greedy/baekjoon_11047.py diff --git a/src/do02reen24/Review/week8.md b/src/do02reen24/Review/week8.md index 8ac2f61..3b0bb11 100644 --- a/src/do02reen24/Review/week8.md +++ b/src/do02reen24/Review/week8.md @@ -7,6 +7,8 @@ ## :ballot_box_with_check: 백준 11047 +- python의 경우 pop을 하면 뒤부터 반환해주기 때문에 array를 통해 쉽게 풀 수 있었다. + ## :ballot_box_with_check: 백준 11497 ## :ballot_box_with_check: 백준 2504 diff --git a/src/do02reen24/greedy/baekjoon_11047.py b/src/do02reen24/greedy/baekjoon_11047.py new file mode 100644 index 0000000..801c5dc --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_11047.py @@ -0,0 +1,14 @@ +import sys + +if __name__ == "__main__": + n, k = map(int, sys.stdin.readline().split(' ')) + coin = [] + ans = 0 + for _ in range(n): + coin.append(int(sys.stdin.readline())) + while coin: + money = coin.pop() + quotient = int(k / money) + k -= quotient * money + ans += quotient + print(ans) \ No newline at end of file From 4ea15cf4558a1f0d04f5b18d31dbb10fbaa8805e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 22 Oct 2020 22:49:24 +0900 Subject: [PATCH 086/193] solve : baekjoon 11497 --- src/do02reen24/Review/week8.md | 2 ++ src/do02reen24/greedy/baekjoon_11497.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 src/do02reen24/greedy/baekjoon_11497.py diff --git a/src/do02reen24/Review/week8.md b/src/do02reen24/Review/week8.md index 3b0bb11..efbc74f 100644 --- a/src/do02reen24/Review/week8.md +++ b/src/do02reen24/Review/week8.md @@ -11,4 +11,6 @@ ## :ballot_box_with_check: 백준 11497 +- 연습하면서 썼던 print문을 안지워서 출력초과가 떴는데 print 출력을 더 유심히 보고 지울 필요가 있을 것 같다. + ## :ballot_box_with_check: 백준 2504 diff --git a/src/do02reen24/greedy/baekjoon_11497.py b/src/do02reen24/greedy/baekjoon_11497.py new file mode 100644 index 0000000..7b187d6 --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_11497.py @@ -0,0 +1,15 @@ +import sys + +if __name__ == "__main__": + T = int(sys.stdin.readline()) + for _ in range(T): + n = int(sys.stdin.readline()) + log = list(map(int, sys.stdin.readline().split(' '))) + log.sort() + level = log[1] - log[0] + lastLevel = log[n-1] - log[n-2] + if lastLevel > level: level = lastLevel + for i in range(0, n - 2): + tempLevel = log[i+2] - log[i] + if tempLevel > level: level = tempLevel + print(level) \ No newline at end of file From 15693cf1644e01457a58f34c0c2ba574905ff89a Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 23 Oct 2020 00:06:12 +0900 Subject: [PATCH 087/193] solve : baekjoon 2504 --- src/do02reen24/Review/week8.md | 2 ++ src/do02reen24/greedy/baekjoon_2504.py | 47 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 src/do02reen24/greedy/baekjoon_2504.py diff --git a/src/do02reen24/Review/week8.md b/src/do02reen24/Review/week8.md index efbc74f..3d5853d 100644 --- a/src/do02reen24/Review/week8.md +++ b/src/do02reen24/Review/week8.md @@ -14,3 +14,5 @@ - 연습하면서 썼던 print문을 안지워서 출력초과가 떴는데 print 출력을 더 유심히 보고 지울 필요가 있을 것 같다. ## :ballot_box_with_check: 백준 2504 + +- 문제를 풀긴했으나 코드를 좀 더 깔끔하게 짤 수 없는지 다른 로직을 고민해본다면 더 좋을 것 같다. diff --git a/src/do02reen24/greedy/baekjoon_2504.py b/src/do02reen24/greedy/baekjoon_2504.py new file mode 100644 index 0000000..937d763 --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_2504.py @@ -0,0 +1,47 @@ +import sys + +def isValidInput(inputs): + stack = [] + try: + for char in inputs: + if char == '(' or char == '[': + stack.append(char) + continue + pre = stack.pop() + if pre == '(' and char == ')':continue + if pre == '[' and char == ']':continue + return False + except: return False + if stack: return False + return True +if __name__ == "__main__": + inputs = str(sys.stdin.readline().strip()) + result = 0 + stack = [] + if not isValidInput(inputs): + print(0) + sys.exit(0) + for char in inputs: + if char == '(' or char == '[': + stack.append(char) + continue + preValue = stack.pop() + if char == ']': + if preValue == '[': + stack.append(3) + continue + elif char == ')': + if preValue == '(': + stack.append(2) + continue + while True: + lastValue = stack.pop() + if lastValue == '(': + stack.append(preValue * 2) + break + elif lastValue == '[': + stack.append(preValue * 3) + break + else: + preValue += lastValue + print(sum(stack)) \ No newline at end of file From 0183fa08542c894f543066c9e31fbf53713ead27 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 23 Oct 2020 01:27:45 +0900 Subject: [PATCH 088/193] =?UTF-8?q?move=20:=20=ED=8F=B4=EB=8D=94=20?= =?UTF-8?q?=EC=9C=84=EC=B9=98=20=EB=B3=80=EA=B2=BD=20week8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=EB=A5=BC=20=EC=B0=A9=EA=B0=81=ED=95=98=EC=97=AC=20?= =?UTF-8?q?=ED=92=80=EC=97=88=EC=8A=B5=EB=8B=88=EB=8B=A4.=20=EC=9D=B4?= =?UTF-8?q?=EC=97=90=20=EC=B9=B4=ED=85=8C=EA=B3=A0=EB=A6=AC=EC=97=90=20?= =?UTF-8?q?=EB=A7=9E=EA=B2=8C=20=ED=8C=8C=EC=9D=BC=EC=9D=84=20=EC=9D=B4?= =?UTF-8?q?=EB=8F=99=ED=95=A9=EB=8B=88=EB=8B=A4.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/{greedy => data-structure}/baekjoon_2504.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/do02reen24/{greedy => data-structure}/baekjoon_2504.py (100%) diff --git a/src/do02reen24/greedy/baekjoon_2504.py b/src/do02reen24/data-structure/baekjoon_2504.py similarity index 100% rename from src/do02reen24/greedy/baekjoon_2504.py rename to src/do02reen24/data-structure/baekjoon_2504.py From 27d8160721960960a98cd88f6615625f2e565cc9 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Fri, 23 Oct 2020 15:37:15 +0900 Subject: [PATCH 089/193] =?UTF-8?q?[WEEK8]=20=EA=B7=B8=EB=A6=AC=EB=94=94?= =?UTF-8?q?=20=EC=95=8C=EA=B3=A0=EB=A6=AC=EC=A6=98=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=EC=97=85=EB=A1=9C=EB=93=9C=20(#23)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1094 문제 - 비트 조작을 통한 풀이 * Add: solve 백준 14889 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 18233 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 1194 문제 - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 * Add: solve 백준 11047 문제 - 그리디 알고리즘을 통한 풀이 * Add: solve 백준 11497 문제 - 그리디 알고리즘을 통한 풀이 * Add: solve 백준 1946 문제 - 그리디 알고리즘을 통한 풀이 --- .../README.md" | 64 +++++++++++++++++++ .../boj_11047.py" | 29 +++++++++ .../boj_11497.py" | 27 ++++++++ .../boj_1946.py" | 18 ++++++ 4 files changed, 138 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" create mode 100644 "src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" create mode 100644 "src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" new file mode 100644 index 0000000..009dbe1 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" @@ -0,0 +1,64 @@ +# 동전 0 + +- 1번 째 시도 (시간 초과) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + for coinKind in coinKinds: + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + K = mindiff + count += 1 + +print(count) +``` + +- 2번째 시도 (한번에 처리) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) +``` \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" new file mode 100644 index 0000000..04d5026 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" @@ -0,0 +1,29 @@ +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" new file mode 100644 index 0000000..f01ed09 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" @@ -0,0 +1,27 @@ +import sys +from collections import deque + +def diff(a, b): + return abs(a-b) + +T = int(sys.stdin.readline()) + +for _ in range(T): + N = int(sys.stdin.readline()) + tongtree = list(map(int, sys.stdin.readline().split())) + newtongtree = deque() + tongtree.sort() + + for item in tongtree: + topIdx = len(newtongtree) + if topIdx <= 1: newtongtree.append(item) + else: + if newtongtree[0] > newtongtree[topIdx-1]: newtongtree.append(item) + else: newtongtree.appendleft(item) + + maxDiff = diff(newtongtree[0], newtongtree[1]) + for idx in range(N-1): + value = diff(newtongtree[idx], newtongtree[idx+1]) + if maxDiff < value: maxDiff = value + + print(maxDiff) \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" new file mode 100644 index 0000000..2b9ec08 --- /dev/null +++ "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" @@ -0,0 +1,18 @@ +import sys + +T = int(sys.stdin.readline()) + +for _ in range(T): + employees = [] + N = int(sys.stdin.readline()) + for _ in range(N): + employees.append(list(map(int, sys.stdin.readline().split()))) + employees.sort() + + testEmployee = employees[0] + count = 1 + for employee in employees: + if testEmployee[1] > employee[1]: + count += 1 + testEmployee = employee + print(count) \ No newline at end of file From 62c5a3e5e5df32e2173a43a57b35937e46ea4c75 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Fri, 23 Oct 2020 15:37:59 +0900 Subject: [PATCH 090/193] =?UTF-8?q?[WEEK8]=20=EA=B7=B8=EB=A6=AC=EB=94=94?= =?UTF-8?q?=20=EC=95=8C=EA=B3=A0=EB=A6=AC=EC=A6=98=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=EC=97=85=EB=A1=9C=EB=93=9C=20(#25)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [week6] 분할정복법 (#17) * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * [WEEK7] 비트마스킹 (#19) * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1094 문제 - 비트 조작을 통한 풀이 * Add: solve 백준 14889 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 18233 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 1194 문제 - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 * [WEEK8] 그리디 알고리즘 문제 업로드 (#23) * Add: solve 백준 2630 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1992 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1780 문제 - 분할정복법을 통한 풀이 * Add: solve 백준 1094 문제 - 비트 조작을 통한 풀이 * Add: solve 백준 14889 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 18233 문제 - 비트마스킹을 통한 풀이 * Add: solve 백준 1194 문제 - 비트마스킹을 통한 풀이 - BFS를 통한 풀이 * Add: solve 백준 11047 문제 - 그리디 알고리즘을 통한 풀이 * Add: solve 백준 11497 문제 - 그리디 알고리즘을 통한 풀이 * Add: solve 백준 1946 문제 - 그리디 알고리즘을 통한 풀이 --- .../README.md" | 64 +++++++++++++++++++ .../boj_11047.py" | 29 +++++++++ .../boj_11497.py" | 27 ++++++++ .../boj_1946.py" | 18 ++++++ 4 files changed, 138 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" create mode 100644 "src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" create mode 100644 "src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" create mode 100644 "src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" new file mode 100644 index 0000000..009dbe1 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/README.md" @@ -0,0 +1,64 @@ +# 동전 0 + +- 1번 째 시도 (시간 초과) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + for coinKind in coinKinds: + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + K = mindiff + count += 1 + +print(count) +``` + +- 2번째 시도 (한번에 처리) +```python +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) +``` \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" new file mode 100644 index 0000000..04d5026 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11047_\353\217\231\354\240\2040/boj_11047.py" @@ -0,0 +1,29 @@ +import sys + +def diff(a, b): + return a-b + +[N, K] = map(int, sys.stdin.readline().split()) + +coinKinds = [] + +for _ in range(N): + coinKinds.append(int(sys.stdin.readline())) + +coinKinds.sort() + +count = 0 +while K!=0: + mindiff = diff(K, coinKinds[0]) + minIdx = 0 + for idx, coinKind in enumerate(coinKinds): + value = diff(K, coinKind) + if value < 0: break + if mindiff > value: + mindiff = value + minIdx = idx + count += K//coinKinds[minIdx] + K -= coinKinds[minIdx] * (K//coinKinds[minIdx]) + + +print(count) \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" new file mode 100644 index 0000000..f01ed09 --- /dev/null +++ "b/src/Do-ho/greedy/boj_11497_\355\206\265\353\202\230\353\254\264/boj_11497.py" @@ -0,0 +1,27 @@ +import sys +from collections import deque + +def diff(a, b): + return abs(a-b) + +T = int(sys.stdin.readline()) + +for _ in range(T): + N = int(sys.stdin.readline()) + tongtree = list(map(int, sys.stdin.readline().split())) + newtongtree = deque() + tongtree.sort() + + for item in tongtree: + topIdx = len(newtongtree) + if topIdx <= 1: newtongtree.append(item) + else: + if newtongtree[0] > newtongtree[topIdx-1]: newtongtree.append(item) + else: newtongtree.appendleft(item) + + maxDiff = diff(newtongtree[0], newtongtree[1]) + for idx in range(N-1): + value = diff(newtongtree[idx], newtongtree[idx+1]) + if maxDiff < value: maxDiff = value + + print(maxDiff) \ No newline at end of file diff --git "a/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" new file mode 100644 index 0000000..2b9ec08 --- /dev/null +++ "b/src/Do-ho/greedy/boj_1946_\354\213\240\354\236\205\354\202\254\354\233\220/boj_1946.py" @@ -0,0 +1,18 @@ +import sys + +T = int(sys.stdin.readline()) + +for _ in range(T): + employees = [] + N = int(sys.stdin.readline()) + for _ in range(N): + employees.append(list(map(int, sys.stdin.readline().split()))) + employees.sort() + + testEmployee = employees[0] + count = 1 + for employee in employees: + if testEmployee[1] > employee[1]: + count += 1 + testEmployee = employee + print(count) \ No newline at end of file From 8a929314c425de58aaa3dcc96349e9f29bc734d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Fri, 23 Oct 2020 18:09:06 +0900 Subject: [PATCH 091/193] boj11497 --- .../Main.java" | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 "src/kyu9341/boj11497_\355\206\265\353\202\230\353\254\264\352\261\264\353\204\210\353\233\260\352\270\260/Main.java" diff --git "a/src/kyu9341/boj11497_\355\206\265\353\202\230\353\254\264\352\261\264\353\204\210\353\233\260\352\270\260/Main.java" "b/src/kyu9341/boj11497_\355\206\265\353\202\230\353\254\264\352\261\264\353\204\210\353\233\260\352\270\260/Main.java" new file mode 100644 index 0000000..1eeb65c --- /dev/null +++ "b/src/kyu9341/boj11497_\355\206\265\353\202\230\353\254\264\352\261\264\353\204\210\353\233\260\352\270\260/Main.java" @@ -0,0 +1,49 @@ +package boj11497_통나무건너뛰기; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class Main { + + static int t; + static int n; + static Deque dq = new ArrayDeque<>(); + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + + while (n-- > 0) { + t = Integer.parseInt(br.readLine()); + ArrayList list = new ArrayList<>(t); + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 0; i < t; i++) { + int cur = Integer.parseInt(st.nextToken()); + list.add(cur); + } + + list.sort(null); + + while (list.size() > 0) { + dq.addLast(list.remove(list.size() - 1)); + if (list.size() == 0) break; + dq.addFirst(list.remove(list.size() - 1)); + } + + int max = 0; + int prev = dq.getLast(); + + while (!dq.isEmpty()) { + int cur = dq.pollFirst(); + int diff = Math.abs(prev - cur); + if (max < diff) max = diff; + prev = cur; + } + + System.out.println(max); + + } + } +} From f31e4df76be4769f018f8bf1ff5787088a23b5cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Fri, 23 Oct 2020 18:09:35 +0900 Subject: [PATCH 092/193] boj11047 --- .../Main.java" | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 "src/kyu9341/boj11047_\353\217\231\354\240\2040/Main.java" diff --git "a/src/kyu9341/boj11047_\353\217\231\354\240\2040/Main.java" "b/src/kyu9341/boj11047_\353\217\231\354\240\2040/Main.java" new file mode 100644 index 0000000..10fb6c2 --- /dev/null +++ "b/src/kyu9341/boj11047_\353\217\231\354\240\2040/Main.java" @@ -0,0 +1,39 @@ +package boj11047_동전0; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Stack; +import java.util.StringTokenizer; + +public class Main { + + static int n; + static int k; + static Stack stack = new Stack<>(); + + 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()); + k = Integer.parseInt(st.nextToken()); + + for (int i = 0; i < n; i++) { + stack.push(Integer.parseInt(br.readLine())); + } + + int cnt = 0; + + while (!stack.isEmpty()) { + int cur = stack.pop(); + if (k >= cur) { + int q = k / cur; + k -= q * cur; + cnt += q; + } + } + System.out.println(cnt); + } +} From 56e20834e39a7282dd06e6ede03a8712e154239c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Fri, 23 Oct 2020 18:10:02 +0900 Subject: [PATCH 093/193] boj1946 --- .../Main.java" | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 "src/kyu9341/boj1946_\354\213\240\354\236\205\354\202\254\354\233\220/Main.java" diff --git "a/src/kyu9341/boj1946_\354\213\240\354\236\205\354\202\254\354\233\220/Main.java" "b/src/kyu9341/boj1946_\354\213\240\354\236\205\354\202\254\354\233\220/Main.java" new file mode 100644 index 0000000..acb20e6 --- /dev/null +++ "b/src/kyu9341/boj1946_\354\213\240\354\236\205\354\202\254\354\233\220/Main.java" @@ -0,0 +1,60 @@ +package boj1946_신입사원; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.StringTokenizer; + +public class Main { + + static int t; + static int n; + + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + t = Integer.parseInt(br.readLine()); + + while (t-- > 0) { + n = Integer.parseInt(br.readLine()); + ArrayList people = new ArrayList<>(); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + int document = Integer.parseInt(st.nextToken()); + int interview = Integer.parseInt(st.nextToken()); + people.add(new Person(document, interview)); + } + + Collections.sort(people); + + int cnt = 0; + int target = people.get(0).interview; + for (int i = 1; i < n; i++) { + if (target < people.get(i).interview) cnt++; + else target = people.get(i).interview; + } + + System.out.println(n - cnt); + } + } + + static class Person implements Comparable{ + int document; + int interview; + + public Person(int document, int interview) { + this.document = document; + this.interview = interview; + } + + @Override + public int compareTo(Person o) { + if (this.document == o.document) return this.interview - o.interview; + return this.document - o.document; + } + } +} From 3315d90c3d2eddaf5685ccc8c04cc9afbf89840e Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 29 Oct 2020 00:06:43 +0900 Subject: [PATCH 094/193] solve : baekjoon 9059 --- src/do02reen24/Review/week9.md | 37 +++++++++++++++++++ .../dynamic-programming/baekjoon_9059.py | 19 ++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/do02reen24/Review/week9.md create mode 100644 src/do02reen24/dynamic-programming/baekjoon_9059.py diff --git a/src/do02reen24/Review/week9.md b/src/do02reen24/Review/week9.md new file mode 100644 index 0000000..d6d366d --- /dev/null +++ b/src/do02reen24/Review/week9.md @@ -0,0 +1,37 @@ +# :fire: week8 + +주제 : Dynamic programming + +## :ballot_box_with_check: 백준 9095 + +- python으로 쉽게 풀 수 있었다. 이전에 작성했던 c++코드를 보니 아래와 같이 푸는 방법도 있었다. + +```c++ +#include +int d[11]; +int main() { + d[0] = 1; + for (int i=1; i<=10; i++) { + if (i-1 >= 0) { + d[i] += d[i-1]; + } + if (i-2 >= 0) { + d[i] += d[i-2]; + } + if (i-3 >= 0) { + d[i] += d[i-3]; + } + } + int t; + scanf("%d",&t); + while (t--) { + int n; + scanf("%d",&n); + printf("%d\n",d[n]); + } +} +``` + +## :ballot_box_with_check: 백준 11727 + +## :ballot_box_with_check: 백준 12865 diff --git a/src/do02reen24/dynamic-programming/baekjoon_9059.py b/src/do02reen24/dynamic-programming/baekjoon_9059.py new file mode 100644 index 0000000..a86e11b --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_9059.py @@ -0,0 +1,19 @@ +import sys +sys.setrecursionlimit(300000) + +def findSum(count, n): + ans = 0 + for i in range(1, 4): + if count == n: + ans += 1 + break + elif count > n: + return 0 + ans += findSum(count + i, n) + return ans + +if __name__ == "__main__": + t = int(sys.stdin.readline()) + for _ in range(t): + n = int(sys.stdin.readline()) + print(findSum(0, n)) \ No newline at end of file From 4de281f02b3127a17cad26a71a3a2b63c37b504b Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 29 Oct 2020 00:26:15 +0900 Subject: [PATCH 095/193] solve : baekjoon 11727 --- src/do02reen24/Review/week9.md | 7 +++++++ src/do02reen24/dynamic-programming/baekjoon_11727.py | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/do02reen24/dynamic-programming/baekjoon_11727.py diff --git a/src/do02reen24/Review/week9.md b/src/do02reen24/Review/week9.md index d6d366d..52ed3ef 100644 --- a/src/do02reen24/Review/week9.md +++ b/src/do02reen24/Review/week9.md @@ -34,4 +34,11 @@ int main() { ## :ballot_box_with_check: 백준 11727 +- 이전에 공부했던 내용을 찾아봐서 풀었다. +- 컴퓨터의 나머지 연산: 컴퓨터의 정수는 저장할 수 있는 범위가 지정되어 있기 때문에 답을 M으로 나눈 나머지를 출력하라는 문제가 등장한다. + - (A+B) mod M = ((A mod M) + (B mod M)) mod M + - (AXB) mod M = ((A mod M) X (B mod M)) mod M + - (A-B) mod M = ((A mod M) - (B mod M)) mod M + - 나누기는 성립하지 않는다. + ## :ballot_box_with_check: 백준 12865 diff --git a/src/do02reen24/dynamic-programming/baekjoon_11727.py b/src/do02reen24/dynamic-programming/baekjoon_11727.py new file mode 100644 index 0000000..4ff854d --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_11727.py @@ -0,0 +1,9 @@ +import sys + +if __name__ == "__main__": + n = int(sys.stdin.readline()) + res = [1 , 1] + for i in range(2, n + 1): + res.append(res[i-1] + res[i-2] + res[i-2]) + res[i] = int(res[i] % 10007) + print(res[n]) \ No newline at end of file From 3931458c6ee4f16029e3196d12daa5655b2657c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B6=8C=EC=98=81=EC=96=B8?= Date: Sun, 1 Nov 2020 11:08:05 +0900 Subject: [PATCH 096/193] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 938e7a7..c6cb887 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,8 @@ | 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | | 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | | 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | -| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평볌한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | | +| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평볌한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | +| 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평볌한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | ## :blue_book: Additional Study From caaa237d76334b84375c1b17424f6068e0ff165f Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 3 Nov 2020 01:01:08 +0900 Subject: [PATCH 097/193] solve : baekjoon 1010 --- src/do02reen24/Review/week10.md | 11 +++++++++++ src/do02reen24/dynamic-programming/baekjoon_1010.py | 12 ++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 src/do02reen24/Review/week10.md create mode 100644 src/do02reen24/dynamic-programming/baekjoon_1010.py diff --git a/src/do02reen24/Review/week10.md b/src/do02reen24/Review/week10.md new file mode 100644 index 0000000..b51a4d2 --- /dev/null +++ b/src/do02reen24/Review/week10.md @@ -0,0 +1,11 @@ +# :fire: week10 + +주제 : Dynamic programming + +## :ballot_box_with_check: 백준 1010 + +- 다리가 겹칠 수 없기 때문에 오른쪽 다리에서 k 개를 선택하고 차례로 이어주면 된다. python의 combination 을 직접 불러 길이를 계산하는 방법도 있었지만, factorial을 쓰는 것이 더 빠를 것 같아 factorial로 구현하였다. + +## :ballot_box_with_check: 백준 2579 + +## :ballot_box_with_check: 백준 1149 diff --git a/src/do02reen24/dynamic-programming/baekjoon_1010.py b/src/do02reen24/dynamic-programming/baekjoon_1010.py new file mode 100644 index 0000000..7e3b1fc --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_1010.py @@ -0,0 +1,12 @@ +import sys +from math import factorial + +def combination(n, c): + return int(factorial(n) / (factorial(n-c) * factorial(c))) + +if __name__ == "__main__": + t = int(sys.stdin.readline()) + for _ in range(t): + n, m = map(int, sys.stdin.readline().split(' ')) + ans = combination(m,n) + print(ans) From a4b6b40e1c9c50cc0e70e698daf654b21557260c Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 7 Nov 2020 17:13:43 +0900 Subject: [PATCH 098/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20117?= =?UTF-8?q?27=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 18 ++++++++++++++++++ .../boj_11727.py" | 12 ++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 "src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/README.md" create mode 100644 "src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/boj_11727.py" diff --git "a/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/README.md" "b/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/README.md" new file mode 100644 index 0000000..72b03b6 --- /dev/null +++ "b/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/README.md" @@ -0,0 +1,18 @@ +# 2*n 타일링 2 + +2*1일때 (1) + +2*1타일 1개 + +2*2일때 (3) +2*1타일 2개 +1*2타일 2개 +2*2타일 1개 + +2*3일때 (6) +이전까지의 타일 + 2*1 +이전전까지의 타일 + (2*2, 1*2타일 2개) + +2*4일때 (12) +이전까지의 타일 + 2*1 +이전전까지의 타일 + (2*2, 1*2타일 2개) \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/boj_11727.py" "b/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/boj_11727.py" new file mode 100644 index 0000000..a440555 --- /dev/null +++ "b/src/Do-ho/dp/boj_11727_2n\355\203\200\354\235\274\353\247\2012/boj_11727.py" @@ -0,0 +1,12 @@ +import sys + +n = int(sys.stdin.readline()) + +D = [0 for _ in range(n+2)] +D[1] = 1 +D[2] = 3 + +for i in range(3, n+1): + D[i] = D[i-1] + 2*D[i-2] + +print(D[n]%10007) \ No newline at end of file From 83f350dbd48976c0795f2803eb7dcf663af2bcda Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 7 Nov 2020 17:13:56 +0900 Subject: [PATCH 099/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20909?= =?UTF-8?q?5=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 32 +++++++++++++++++++ .../boj_9095.py" | 15 +++++++++ 2 files changed, 47 insertions(+) create mode 100644 "src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/README.md" create mode 100644 "src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/boj_9095.py" diff --git "a/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/README.md" "b/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/README.md" new file mode 100644 index 0000000..c272261 --- /dev/null +++ "b/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/README.md" @@ -0,0 +1,32 @@ +# 1,2,3 더하기 + +1일 때 +1 + +2일 때 +1+1 +2 + +3일 때 +1+1+1 +1+2 +2+1 +3 + +4일 때 +1+1+1+1 +1+1+2 +1+2+1 +2+1+1 +2+2 +1+3 +3+1 + +1의 경우에 수에 3을 더한 경우의 수 +2의 경우에 수에 2를 더한 경우의 수 +3의 경우에 수에 1을 더한 경우의 수 + +F(1) + 3 -> 1 +F(2) + 2 -> 2 +F(3) + 1 -> 4 +F(4) = F(1) + F(2) + F(3) = 7 \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/boj_9095.py" "b/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/boj_9095.py" new file mode 100644 index 0000000..b6b2e95 --- /dev/null +++ "b/src/Do-ho/dp/boj_9096_123\353\215\224\355\225\230\352\270\260/boj_9095.py" @@ -0,0 +1,15 @@ +import sys + +T = int(sys.stdin.readline()) + +D = [0 for _ in range(12)] +D[1] = 1 +D[2] = 2 +D[3] = 4 + +for i in range(4, 12): + D[i] = D[i-3] + D[i-2] + D[i-1] + +for _ in range(T): + n = int(sys.stdin.readline()) + sys.stdout.write(str(D[n])+'\n') \ No newline at end of file From 3fa6b60a75ad76183584f8b29689ef7f7c96efe4 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 7 Nov 2020 17:44:29 +0900 Subject: [PATCH 100/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20101?= =?UTF-8?q?0=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 19 +++++++++++++++++++ .../boj_1010.py" | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 "src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/README.md" create mode 100644 "src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/boj_1010.py" diff --git "a/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/README.md" "b/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/README.md" new file mode 100644 index 0000000..0411f88 --- /dev/null +++ "b/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/README.md" @@ -0,0 +1,19 @@ +# 다리 놓기 + +f(1, 1) = 1 +f(1, 2) = 2 +f(1, 3) = 3 +~~ + +f(2, 2) = f(1, 1) +f(2, 3) = f(1, 2) + f(1, 1) +f(2, 4) = f(1, 3) + f(1, 2) + f(1, 1) = f(1, 3) + f(2, 3) +f(3, 3) = f(2, 2) +f(3, 4) = f(2, 3) + f(2, 2) +f(3, 5) = f(2, 4) + f(2, 3) + f(2, 2) = f(2, 4) + f(3, 4) + +따라서 점화식 + +f(n, k) = f(n-1, k-1) + f(n, k-1) + = f(n, k-1) + f(n-1, k-1) + diff --git "a/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/boj_1010.py" "b/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/boj_1010.py" new file mode 100644 index 0000000..26395dc --- /dev/null +++ "b/src/Do-ho/dp/boj_1010_\353\213\244\353\246\254\353\206\223\352\270\260/boj_1010.py" @@ -0,0 +1,19 @@ +import sys + +D = [[0 for _ in range(30)] for _ in range(30)] + +def f(i, j): + if j Date: Sat, 7 Nov 2020 19:09:39 +0900 Subject: [PATCH 101/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20257?= =?UTF-8?q?9=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 19 +++++++++++++++++++ .../boj_2579.py" | 17 +++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 "src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/README.md" create mode 100644 "src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/boj_2579.py" diff --git "a/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/README.md" "b/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/README.md" new file mode 100644 index 0000000..89fc4bf --- /dev/null +++ "b/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/README.md" @@ -0,0 +1,19 @@ +# 계단 오르기 + +처음 생각난 것은 베스킨라빈스 생각남... +필승법.. + +마지막을 무조건 부르면 지는 게임에서 똑같이 3단계를 고려했을 때 +4단계를 고려하면 이기는 게임 + +마지막을 무조건 밟아야하므로 마지막으로부터 필승법을 생각! + +마지막 이전꺼를 밟을 경우 = 마지막 점수 + 마지막 이전꺼 점수 + 마지막 전전전꺼까지의 최고값 + +마지막 전전꺼를 밟는 경우 = 마지막 점수 + 마지막 전전꺼까지의 최고값 + +점화식으로 보면 + +f(n) = s(n) + s(n-1) + f(n-3) +f(n) = s(n) + f(n-2) +단 n>3 \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/boj_2579.py" "b/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/boj_2579.py" new file mode 100644 index 0000000..cbbda76 --- /dev/null +++ "b/src/Do-ho/dp/boj_2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/boj_2579.py" @@ -0,0 +1,17 @@ +import sys + +T = int(sys.stdin.readline()) +S = [0 for _ in range(T)] +D = [0 for _ in range(T)] + +for i in range(T): + S[i] = int(sys.stdin.readline()) + +D[0] = S[0] +if T>1: D[1] = S[1] + D[0] +if T>2: D[2] = max(S[0]+S[2], S[1]+S[2]) + +for i in range(3, T): + D[i] = max(S[i] + S[i-1] + D[i-3], S[i] + D[i-2]) + +print(D[T-1]) \ No newline at end of file From c6216ab3fc0f9b50de2c7aeca68c14469a70441c Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 7 Nov 2020 19:36:38 +0900 Subject: [PATCH 102/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20114?= =?UTF-8?q?9=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 3 +++ .../boj_1149.py" | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 "src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/README.md" create mode 100644 "src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/boj_1149.py" diff --git "a/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/README.md" "b/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/README.md" new file mode 100644 index 0000000..4c0bca6 --- /dev/null +++ "b/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/README.md" @@ -0,0 +1,3 @@ +# RGB거리 + +순차적으로 2차원 D에 저장하면서 마지막 3개의 값을 비교하자 diff --git "a/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/boj_1149.py" "b/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/boj_1149.py" new file mode 100644 index 0000000..ec09113 --- /dev/null +++ "b/src/Do-ho/dp/boj_1149_RGB\352\261\260\353\246\254/boj_1149.py" @@ -0,0 +1,17 @@ +import sys + +T = int(sys.stdin.readline()) +D = [[0, 0, 0] for _ in range(T)] +S = [] + +for _ in range(T): + S.append(list(map(int, sys.stdin.readline().split()))) + +D[0] = S[0] + +for i in range(1, T): + D[i][0] = S[i][0] + min(D[i-1][1], D[i-1][2]) + D[i][1] = S[i][1] + min(D[i-1][0], D[i-1][2]) + D[i][2] = S[i][2] + min(D[i-1][0], D[i-1][1]) + +sys.stdout.write(str(min(D[T-1]))) \ No newline at end of file From 1e532c39994af54309f2872f855983c649e55609 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 7 Nov 2020 21:14:53 +0900 Subject: [PATCH 103/193] =?UTF-8?q?boj=20=EB=8B=A4=EB=A6=AC=20=EB=86=93?= =?UTF-8?q?=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Main.java" | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 "src/kyu9341/boj2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/Main.java" diff --git "a/src/kyu9341/boj2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/Main.java" "b/src/kyu9341/boj2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/Main.java" new file mode 100644 index 0000000..4fed3df --- /dev/null +++ "b/src/kyu9341/boj2579_\352\263\204\353\213\250\354\230\244\353\245\264\352\270\260/Main.java" @@ -0,0 +1,31 @@ +package boj2579_계단오르기; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Main { + + static final int MAX = 300; + static int d[][] = new int[MAX + 1][3]; + static int score[] = new int[MAX + 1]; + static int n; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + + for (int i = 1; i <= n; i++) score[i] = Integer.parseInt(br.readLine()); + + d[1][1] = score[1]; + d[1][2] = score[1]; + + for (int i = 2 ; i<= n; i++) { + d[i][1] = d[i - 1][2] + score[i]; + d[i][2] = Math.max(d[i - 2][1] + score[i], d[i - 2][2] + score[i]); + } + + System.out.println(Math.max(d[n][1], d[n][2])); + + } +} From 060a9c7f4ef18aae53b4f355b0335523aa62fa28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 7 Nov 2020 21:16:40 +0900 Subject: [PATCH 104/193] =?UTF-8?q?boj=20=EB=8B=A4=EB=A6=AC=20=EB=86=93?= =?UTF-8?q?=EA=B8=B0:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Main.java" | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 "src/kyu9341/boj1010_\353\213\244\353\246\254\353\206\223\352\270\260/Main.java" diff --git "a/src/kyu9341/boj1010_\353\213\244\353\246\254\353\206\223\352\270\260/Main.java" "b/src/kyu9341/boj1010_\353\213\244\353\246\254\353\206\223\352\270\260/Main.java" new file mode 100644 index 0000000..5edf30e --- /dev/null +++ "b/src/kyu9341/boj1010_\353\213\244\353\246\254\353\206\223\352\270\260/Main.java" @@ -0,0 +1,45 @@ +package boj1010_다리놓기; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + + static int t; + static int n, m; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + t = Integer.parseInt(br.readLine()); + + while (t-- > 0) { + st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + int max = Math.max(n, m - n); + int min = Math.min(n, m - n); + + long tmp = 1; + for (int i = m; i >= max + 1; i--) { + tmp *= i; + } + + long res = tmp / getFactorial(min); + System.out.println(res); + } + + } + + static long getFactorial(int n) { + long res = 1; + while (n > 0) { + res *= n--; + } + return res; + } + + +} From bc7c65dc70b58a2db37e2a82f0d0fc731a08398a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sat, 7 Nov 2020 21:17:04 +0900 Subject: [PATCH 105/193] =?UTF-8?q?boj=20RGB=20=EA=B1=B0=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Main.java" | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 "src/kyu9341/boj1149_RGB\352\261\260\353\246\254/Main.java" diff --git "a/src/kyu9341/boj1149_RGB\352\261\260\353\246\254/Main.java" "b/src/kyu9341/boj1149_RGB\352\261\260\353\246\254/Main.java" new file mode 100644 index 0000000..085c3dc --- /dev/null +++ "b/src/kyu9341/boj1149_RGB\352\261\260\353\246\254/Main.java" @@ -0,0 +1,44 @@ +package boj1149_RGB거리; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + final static int MAX = 1000; + final static int RED = 0; + final static int GREEN = 1; + final static int BLUE = 2; + + static int n; + static int d[][] = new int[MAX + 1][3]; + static int cost[][] = new int[MAX + 1][3]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + n = Integer.parseInt(br.readLine()); + + for (int i = 1; i <= n; i++) { + st = new StringTokenizer(br.readLine()); + cost[i][RED] = Integer.parseInt(st.nextToken()); + cost[i][GREEN] = Integer.parseInt(st.nextToken()); + cost[i][BLUE] = Integer.parseInt(st.nextToken()); + } + + d[1][RED] = cost[1][RED]; + d[1][GREEN] = cost[1][GREEN]; + d[1][BLUE] = cost[1][BLUE]; + + for (int i = 1; i <= n; i++) { + d[i][RED] = Math.min(d[i - 1][GREEN], d[i - 1][BLUE]) + cost[i][RED]; + d[i][GREEN] = Math.min(d[i - 1][RED], d[i - 1][BLUE]) + cost[i][GREEN]; + d[i][BLUE] = Math.min(d[i - 1][GREEN], d[i - 1][RED]) + cost[i][BLUE]; + } + + int min = Math.min(d[n][RED], Math.min(d[n][GREEN], d[n][BLUE])); + System.out.println(min); + + } +} From be2cde59f17d507a9a44c02f76132c2b3362410d Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sun, 8 Nov 2020 11:12:53 +0900 Subject: [PATCH 106/193] Update README.md --- README.md | 47 +++++++++++++++++++++++------------------------ 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index c6cb887..ed0786e 100644 --- a/README.md +++ b/README.md @@ -12,31 +12,32 @@ ## :ledger: 진행방식 -* 매주 하나의 주제(DP, BFS 등)를 정해서 문제풀이 -* 매주 한명당 1문제씩 문제 선정 후 업로드 -* 주마다 코드 및 설명을 업로드 -* 자신이 사용하고 싶은 언어로 풀이 -* Github 활용 - * Repository를 Fork해온다. - * 문제를 풀고 **문제 단위**로 commit을 한다. - * ```src/개인 폴더/```에 업로드한다. - * 각자 브랜치로 PR을 보낸다. - * 코드 리뷰가 끝나고 master Branch로 Merge한다. +- 매주 하나의 주제(DP, BFS 등)를 정해서 문제풀이 +- 매주 한명당 1문제씩 문제 선정 후 업로드 +- 주마다 코드 및 설명을 업로드 +- 자신이 사용하고 싶은 언어로 풀이 +- Github 활용 + - Repository를 Fork해온다. + - 문제를 풀고 **문제 단위**로 commit을 한다. + - `src/개인 폴더/`에 업로드한다. + - 각자 브랜치로 PR을 보낸다. + - 코드 리뷰가 끝나고 master Branch로 Merge한다. ## :green_book: Week Study -| | 1 | 2 | 3 | 4 | -| ----- | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------: | :----------------------------------------------------------: | -| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | -| 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | -| 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | -| 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | -| 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | -| 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | -| 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | -| 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | -| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평볌한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | -| 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평볌한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | +| | 1 | 2 | 3 | 4 | +| ------ | :------------------------------------------------------------------: | :-------------------------------------------------------------------------: | :-----------------------------------------------------: | :-----------------------------------------------------------: | +| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | +| 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | +| 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | +| 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | +| 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | +| 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | +| 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | +| 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | +| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | +| 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평범한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | +| 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | ## :blue_book: Additional Study @@ -45,8 +46,6 @@ | 자료구조 | [괄호](https://www.acmicpc.net/problem/9012) | [쇠막대기](https://www.acmicpc.net/problem/10799) | [스택 수열](https://www.acmicpc.net/problem/1874) | | BFS/DFS | [DFS와 BFS](https://www.acmicpc.net/problem/1260) | | | - - ## :raising_hand: Contributors | [grap3fruit](https://github.com/grap3fruit) | [**kyu9341**](https://github.com/kyu9341) | From 25c47707477415bbf536f309f97647068a3ba5ec Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sun, 8 Nov 2020 11:42:16 +0900 Subject: [PATCH 107/193] Add: Upload week8,9,10 code and readme file --- src/grap3fruit/boj/1010.md | 11 +++ src/grap3fruit/boj/1010.py | 25 +++++++ src/grap3fruit/boj/11047.md | 8 +++ src/grap3fruit/boj/11047.py | 20 ++++++ src/grap3fruit/boj/1149.md | 135 +++++++++++++++++++++++++++++++++++ src/grap3fruit/boj/1149.py | 120 +++++++++++++++++++++++++++++++ src/grap3fruit/boj/11497.md | 12 ++++ src/grap3fruit/boj/11497.py | 27 +++++++ src/grap3fruit/boj/11727.md | 15 ++++ src/grap3fruit/boj/11727.py | 21 ++++++ src/grap3fruit/boj/1946.md | 7 ++ src/grap3fruit/boj/1946.py | 30 ++++++++ src/grap3fruit/boj/2579.md | 27 +++++++ src/grap3fruit/boj/2579.py | 54 ++++++++++++++ src/grap3fruit/boj/9095.md | 44 ++++++++++++ src/grap3fruit/boj/9095.py | 25 +++++++ src/grap3fruit/input_test.py | 37 ++++++++++ 17 files changed, 618 insertions(+) create mode 100644 src/grap3fruit/boj/1010.md create mode 100644 src/grap3fruit/boj/1010.py create mode 100644 src/grap3fruit/boj/11047.md create mode 100644 src/grap3fruit/boj/11047.py create mode 100644 src/grap3fruit/boj/1149.md create mode 100644 src/grap3fruit/boj/1149.py create mode 100644 src/grap3fruit/boj/11497.md create mode 100644 src/grap3fruit/boj/11497.py create mode 100644 src/grap3fruit/boj/11727.md create mode 100644 src/grap3fruit/boj/11727.py create mode 100644 src/grap3fruit/boj/1946.md create mode 100644 src/grap3fruit/boj/1946.py create mode 100644 src/grap3fruit/boj/2579.md create mode 100644 src/grap3fruit/boj/2579.py create mode 100644 src/grap3fruit/boj/9095.md create mode 100644 src/grap3fruit/boj/9095.py create mode 100644 src/grap3fruit/input_test.py diff --git a/src/grap3fruit/boj/1010.md b/src/grap3fruit/boj/1010.md new file mode 100644 index 0000000..2348a68 --- /dev/null +++ b/src/grap3fruit/boj/1010.md @@ -0,0 +1,11 @@ +# 1010 - 성공 + +## DP + +- nCr 써서 풀었음. +- 7C3이면 (7*6*5)/(3*2*1)을 계산. + +## 보완 + +- DP문제인데 DP로 안풀었다. 😂 +- 도호님 방법 처럼 DP로 풀어볼 필요도 있을듯.. diff --git a/src/grap3fruit/boj/1010.py b/src/grap3fruit/boj/1010.py new file mode 100644 index 0000000..2de67de --- /dev/null +++ b/src/grap3fruit/boj/1010.py @@ -0,0 +1,25 @@ +import sys + +def get_mCn(N, M): + mom = N + mom_index = N + child = M + child_index = M + + for _ in range(M-1): + + mom = mom * (mom_index-1) + mom_index -= 1 + + while child_index > 1: + child = child * (child_index-1) + child_index -= 1 + + return(int(mom/child)) + +T = int(sys.stdin.readline()) + +for _ in range(T): + N, M = list(map(int,sys.stdin.readline().strip().split())) + print(get_mCn(M, N)) + diff --git a/src/grap3fruit/boj/11047.md b/src/grap3fruit/boj/11047.md new file mode 100644 index 0000000..27c915b --- /dev/null +++ b/src/grap3fruit/boj/11047.md @@ -0,0 +1,8 @@ +# 11047 - 성공 + +## 그리디 알고리즘 + +- 동전의 가치를 내림차순으로 다시 정렬 한 후에, +- 큰 동전부터 주어진 K원을 나누어 간다. +- 나누어 떨어지면 그만큼 빼고 진행한다. +- 모든 코인에 대해서 진행 하고 나면 나눠진 횟수 출력. diff --git a/src/grap3fruit/boj/11047.py b/src/grap3fruit/boj/11047.py new file mode 100644 index 0000000..fdb1a82 --- /dev/null +++ b/src/grap3fruit/boj/11047.py @@ -0,0 +1,20 @@ +import sys + +N, K = list(map(int,sys.stdin.readline().strip().split())) + +coins = [] +for i in range(N): + coins.append(int(sys.stdin.readline())) + +coins.sort(reverse=True) +print(coins) + +count = 0 +for coin in coins: + value = int(K/coin) + + if value >= 1: + count += value + K = K-(value*coin) + +print(count) \ No newline at end of file diff --git a/src/grap3fruit/boj/1149.md b/src/grap3fruit/boj/1149.md new file mode 100644 index 0000000..e3e69f9 --- /dev/null +++ b/src/grap3fruit/boj/1149.md @@ -0,0 +1,135 @@ +# 1149 - 실패 + +## DP + +```python +def get_min(datum): + min = [datum[0],'R'] + if datum[1] < min[0]: + min = [datum[1],'G'] + if datum[2] < min[0]: + min = [datum[2],'B'] + return min +``` + +[value, color] 형태로 최소값을 반환 + +ex) get_min(1,2,3) → [1,'R'] + +```python +def get_min_dp_n_1(dp_N_1, a_N): + result = [] + if dp_N_1[1] == 'R': + if a_N[1] < a_N[2] : + return [dp_N_1[0] + a_N[1],'G'] + return [dp_N_1[0] + a_N[2],'B'] + + elif dp_N_1[1] == 'G': + if a_N[0] < a_N[2] : + return [dp_N_1[0] + a_N[0],'R'] + return [dp_N_1[0] + a_N[2],'B'] + + elif dp_N_1[1] == 'B': + if a_N[0] < a_N[1] : + return [dp_N_1[0] + a_N[0],'R'] + return [dp_N_1[0] + a_N[1],'G'] +``` + +식 : dp[n] = dp[n-1] + a[n] + +dp[n-1]의 색과 다른 a[n]번째 경우의 수 중에서, 합의 최솟값을 구함. + +[value, color] 형태로 최소값을 반환 + +```python +def get_min_n_1_n_2(color, a_N_1, a_N): + result = [] + min = 2001 + if color == 'R': + if a_N_1[1] + a_N[0] < min : # G + R + min = a_N_1[1] + a_N[0] + result = [min, 'R'] + if a_N_1[1] + a_N[2] < min : # G + B + min = a_N_1[1] + a_N[2] + result = [min, 'B'] + if a_N_1[2] + a_N[0] < min : # B + R + min = a_N_1[2] + a_N[0] + result = [min, 'R'] + if a_N_1[2] + a_N[1] < min : # B + G + min = a_N_1[2] + a_N[1] + result = [min, 'G'] + + min = 2001 + if color == 'G': + if a_N_1[0] + a_N[1] < min : # R + G + min = a_N_1[0] + a_N[1] + result = [min, 'G'] + if a_N_1[0] + a_N[2] < min : # R + B + min = a_N_1[0] + a_N[2] + result = [min, 'B'] + if a_N_1[2] + a_N[1] < min : # B + G + min = a_N_1[2] + a_N[1] + result = [min, 'G'] + if a_N_1[2] + a_N[0] < min : # B + R + min = a_N_1[2] + a_N[0] + result = [min, 'R'] + + min = 2001 + if color == 'B': + if a_N_1[0] + a_N[1] < min : # R + G + min = a_N_1[0] + a_N[1] + result = [min, 'G'] + if a_N_1[0] + a_N[2] < min : # R + B + min = a_N_1[0] + a_N[2] + result = [min, 'B'] + if a_N_1[1] + a_N[0] < min : # G + R + min = a_N_1[1] + a_N[0] + result = [min, 'R'] + if a_N_1[1] + a_N[2] < min : # G + B + min = a_N_1[1] + a_N[2] + result = [min, 'B'] + + return result +``` + +식 : dp[n] = dp[n-2] + a[n-1] + a[n] + +dp[n-2]번째의 색과 다른 경우의 수 a[n-1]을 더하고, a[n-1]의 색과 다른 경우의 수 a[n]을 더해 dp[n]을 구함. + +앞의 2,3번 함수를 통해 나온 값의 최소값을 dp[n]으로 함. + +--- + +## 안풀림 ㅠㅠ + +### 반례 1 + +```python +// 입력 +3 +1 9 2 +1 9 9 +9 1 9 + +// 정답 +4 +``` + +dp[1] 보완해줘서 해결 + +### 반례 2 + +```python +3 +1 2 3 +1 2 3 +100 1 100 + +# 정답 +4 + +# 출력 +5 +``` + +> 나중에 성공시켜 업데이트 꼭 하자. diff --git a/src/grap3fruit/boj/1149.py b/src/grap3fruit/boj/1149.py new file mode 100644 index 0000000..ca49869 --- /dev/null +++ b/src/grap3fruit/boj/1149.py @@ -0,0 +1,120 @@ +import sys + +N = int(sys.stdin.readline()) + +data = [] +for _ in range(N): + RGB = list(map(int,sys.stdin.readline().strip().split())) + data.append(RGB) + +print(data) + +def get_min(datum): + min = [datum[0],'R'] + if datum[1] < min[0]: + min = [datum[1],'G'] + if datum[2] < min[0]: + min = [datum[2],'B'] + return min + +def get_min_dp_n_1(dp_N_1, a_N): + result = [] + if dp_N_1[1] == 'R': + if a_N[1] < a_N[2] : + return [dp_N_1[0] + a_N[1],'G'] + return [dp_N_1[0] + a_N[2],'B'] + + elif dp_N_1[1] == 'G': + if a_N[0] < a_N[2] : + return [dp_N_1[0] + a_N[0],'R'] + return [dp_N_1[0] + a_N[2],'B'] + + elif dp_N_1[1] == 'B': + if a_N[0] < a_N[1] : + return [dp_N_1[0] + a_N[0],'R'] + return [dp_N_1[0] + a_N[1],'G'] + +def get_min_n_1_n_2(color, a_N_1, a_N): + result = [] + min = 2001 + if color == 'R': + if a_N_1[1] + a_N[0] < min : # G + R + min = a_N_1[1] + a_N[0] + result = [min, 'R'] + if a_N_1[1] + a_N[2] < min : # G + B + min = a_N_1[1] + a_N[2] + result = [min, 'B'] + if a_N_1[2] + a_N[0] < min : # B + R + min = a_N_1[2] + a_N[0] + result = [min, 'R'] + if a_N_1[2] + a_N[1] < min : # B + G + min = a_N_1[2] + a_N[1] + result = [min, 'G'] + + min = 2001 + if color == 'G': + if a_N_1[0] + a_N[1] < min : # R + G + min = a_N_1[0] + a_N[1] + result = [min, 'G'] + if a_N_1[0] + a_N[2] < min : # R + B + min = a_N_1[0] + a_N[2] + result = [min, 'B'] + if a_N_1[2] + a_N[1] < min : # B + G + min = a_N_1[2] + a_N[1] + result = [min, 'G'] + if a_N_1[2] + a_N[0] < min : # B + R + min = a_N_1[2] + a_N[0] + result = [min, 'R'] + + min = 2001 + if color == 'B': + if a_N_1[0] + a_N[1] < min : # R + G + min = a_N_1[0] + a_N[1] + result = [min, 'G'] + if a_N_1[0] + a_N[2] < min : # R + B + min = a_N_1[0] + a_N[2] + result = [min, 'B'] + if a_N_1[1] + a_N[0] < min : # G + R + min = a_N_1[1] + a_N[0] + result = [min, 'R'] + if a_N_1[1] + a_N[2] < min : # G + B + min = a_N_1[1] + a_N[2] + result = [min, 'B'] + + return result + +# print(get_min_n_1_n_2('R', [26,40,83],[49,60,57])) + + +def get_min_dp_n_2(dp_N_2, a_N_1, a_N): + result = [] + + result = get_min_n_1_n_2(dp_N_2[1], a_N_1, a_N) + result[0] += dp_N_2[0] + print("n-2",result) + return result + +# print(get_min_n_1([26,'R'], [49,60,70])) + +def calc(): + dp = [0]*1001 + + dp[0] = get_min(data[0]) + if N == 1: + return dp[0][0] + + dp[1] = min(get_min_dp_n_1([data[0][0],'R'], data[1]),get_min_dp_n_1([data[0][1],'G'], data[1]),get_min_dp_n_1([data[0][2],'B'], data[1])) + if N == 2: + return dp[1][0] + + for i in range(2, N): + test1 = get_min_dp_n_2(dp[i-2], data[i-1], data[i]) + test2 = get_min_dp_n_1(dp[i-1], data[i]) + print(test1, test2) + dp[i] = min(test1, test2) + # dp[i] = min(get_min_dp_n_2(dp[i-2], data[i-1], data[i]), get_min_dp_n_1(dp[i-1], data[i])) + + print(dp) + return dp[N-1][0] + +print(calc()) diff --git a/src/grap3fruit/boj/11497.md b/src/grap3fruit/boj/11497.md new file mode 100644 index 0000000..34bf471 --- /dev/null +++ b/src/grap3fruit/boj/11497.md @@ -0,0 +1,12 @@ +# 11497 - 성공 + +## 그리디 알고리즘 + +- 가운데 가장 큰 수를 놓고, 그 옆 좌,우로 차례차례 그 다음 큰 수를 놓는다. +- 그러면 모든 경우에서 양옆의 차가 최소가 되는 경우가 완성된다. +- 반대로 해도 동작될 듯 하다. +- deque 활용해서, 좌우로 값을 넣어줬다. + +## 보완 + +- 아이디어 싸움인데, 증명하기도 뭔가 어려웠고. 더 연습과 학습이 필요하다.. diff --git a/src/grap3fruit/boj/11497.py b/src/grap3fruit/boj/11497.py new file mode 100644 index 0000000..702dd8d --- /dev/null +++ b/src/grap3fruit/boj/11497.py @@ -0,0 +1,27 @@ +import sys +import collections + +T = int(sys.stdin.readline()) +for i in range(T): + deq = collections.deque([]) + N = int(sys.stdin.readline()) + datas = list(map(int,sys.stdin.readline().strip().split())) + datas.sort(reverse=True) + + count = 0 + for data in datas: + if count % 2 == 0: + deq.append(data) + if count % 2 == 1: + deq.appendleft(data) + + count += 1 + + print(deq) + max_gap = 0 + for j in range(-1, N-1): + gap = abs(deq[j]-deq[j+1]) + if gap > max_gap: + max_gap = gap + + print(max_gap) diff --git a/src/grap3fruit/boj/11727.md b/src/grap3fruit/boj/11727.md new file mode 100644 index 0000000..7fec9bb --- /dev/null +++ b/src/grap3fruit/boj/11727.md @@ -0,0 +1,15 @@ +# 11727 - 성공 (힌트) + +## DP + +![image](https://user-images.githubusercontent.com/13213473/98455510-fbf68880-21b4-11eb-953f-5612eb6bef77.png) + +위 그림에서 N번째 경우의 수는 + +N-1번째에 2x1 추가해준 경우와, N-2번째에 1x2를 두개 추가해준 경우를 합한 것과 같다. + +따라서 식은 `dp[N] = dp[N-1] + dp[N-2]` + +11727번 문제는 위 그림에서 N-2번째에 2x2를 추가하는 경우를 하나 더 생각하면 된다. + +따라서 식은 `dp[N] = dp[N-1] + dp[N-2] + dp[N-2]` diff --git a/src/grap3fruit/boj/11727.py b/src/grap3fruit/boj/11727.py new file mode 100644 index 0000000..0adaa4f --- /dev/null +++ b/src/grap3fruit/boj/11727.py @@ -0,0 +1,21 @@ +import sys + +N = int(sys.stdin.readline()) + +dp = [0]*1002 +dp[1] = 1 +dp[2] = 3 + +index = 2 +while True: + if N == 1: + print(dp[1]) + break + + if index == N: + print(dp[N]%10007) + break + + index += 1 + dp[index] = dp[index-1] + dp[index-2] + dp[index-2] + \ No newline at end of file diff --git a/src/grap3fruit/boj/1946.md b/src/grap3fruit/boj/1946.md new file mode 100644 index 0000000..c122a03 --- /dev/null +++ b/src/grap3fruit/boj/1946.md @@ -0,0 +1,7 @@ +# 1946 - 성공 + +## 그리디 알고리즘 + +- 먼저 [i][0]을 정렬해줌. +- [i][0]은 [j][0]보다 항상 큰 상태, 여기서 [i][1] 마저 크면, 선발되지 않는다. +- 선발되지 않는 수를 구해서, 전체 수에서 빼서 결과 도출. diff --git a/src/grap3fruit/boj/1946.py b/src/grap3fruit/boj/1946.py new file mode 100644 index 0000000..2ac9c79 --- /dev/null +++ b/src/grap3fruit/boj/1946.py @@ -0,0 +1,30 @@ +import sys + +def check_score(score_list): + count = 0 + + for i in range(0,len(score_list)-1): + check = False + for j in range(i+1, len(score_list)): + print(i,j, score_list[i][1], score_list[j][1]) + if score_list[i][1] > score_list[j][1]: #[i][0]은 [j][0]보다 항상 큰 상태, 여기서 [1] 마저 크면, + print(i,j) + check = True + count += 1 + break + + return count + + +if __name__ == "__main__": + T = int(sys.stdin.readline()) + for i in range(T): + N = int(sys.stdin.readline()) + score_list = [] + for j in range(N): + score_list.append(list(map(int,sys.stdin.readline().strip().split()))) + + score_list.sort(reverse=True) + print(score_list) + print("Score:", N - check_score(score_list)) + diff --git a/src/grap3fruit/boj/2579.md b/src/grap3fruit/boj/2579.md new file mode 100644 index 0000000..c128db7 --- /dev/null +++ b/src/grap3fruit/boj/2579.md @@ -0,0 +1,27 @@ +# 2579 - 성공 (힌트) + +## DP + +dp[1], dp[2], dp[3] 베이스로 구하고 + +``` +dp[n] = max( + +dp[n-2] + a[n] , + +dp[n-3] + a[n-1] + a[n] + + ) +``` + +a[n]번째를 밟기 위해선 아래 두가지 케이스가 와야한다. +a[n-2] → 0 → a[n] [n-2]번째를 밟는 경우. +a[n-3] → 0 → a[n-1] → a[n] [n-3]번째를 밟는 경우. + +이 두 경우중 하나가 a[n]번째의 경우의 수로써 가능하고, +이때 최소값을 구하면 된다. +따라서 점화식이 위와 같이 된다. + +## 보완 + +- 힌트보고 풀었다. dp 감이 슬슬 잡히긴 하는데 여전히 쉽지 않다 😥 diff --git a/src/grap3fruit/boj/2579.py b/src/grap3fruit/boj/2579.py new file mode 100644 index 0000000..4642a0e --- /dev/null +++ b/src/grap3fruit/boj/2579.py @@ -0,0 +1,54 @@ +import sys + +N = int(sys.stdin.readline()) + +score_list = [] +for _ in range(N): + score_list.append(int(sys.stdin.readline())) + +def get_dp_3(a,b,c,d): + max = a+b+d + if a+c+d > max: + max = a+c+d + + if b+c > max: + max = b+c + + return max + +def get_max(a,b): + if a>b: + return a + + return b + +def calc(score_list): + dp = [0]*301 + dp[0] = score_list[0] + if N==1 : + print(dp[0]) + return + + dp[1] = score_list[1] + score_list[0] + if N==2 : + print(dp[1]) + return + + dp[2] = get_max(score_list[0],score_list[1]) + score_list[2] + if N==3 : + print(dp[2]) + return + + dp[3] = get_dp_3(score_list[0],score_list[1],score_list[2],score_list[3]) + if N==4 : + print(dp[3]) + return + + print(dp[0],dp[1],dp[2],dp[3]) + for i in range(4, N): + dp[i] = get_max(dp[i-2], dp[i-3]+score_list[i-1])+score_list[i] + print(i, dp[i]) + print(dp[len(score_list)-1]) + return + +calc(score_list) \ No newline at end of file diff --git a/src/grap3fruit/boj/9095.md b/src/grap3fruit/boj/9095.md new file mode 100644 index 0000000..e7d2515 --- /dev/null +++ b/src/grap3fruit/boj/9095.md @@ -0,0 +1,44 @@ +# 9095 - 성공 (힌트) + +## DP + +base dp 를 1,2,3으로 두고 + +``` +4 = 1+3 += 2+2 += 3+1 + +dp[4] = 1 + dp[3] += 2 + dp[2] += 3 + dp[1] + +5 = 1+4 += 2+3 += 3+2 + +dp[5] = 1 + dp[4] += 2 + dp[3] += 3 + dp[2] + +6 = 1+5 += 2+4 += 3+3 + +dp[n] = 1 + dp[n-1] += 2 + dp[n-2] += 3 + dp[n-3] +``` + +1,2,3은 값이 아니라, 경우의 수 이다. +1 + dp[n-1] 이 되는 경우의 수, +2 + dp[n-2] 이 되는 경우의 수, +3 + dp[n-3] 이 되는 경우의 수 +이 3 종류 경우의 수가 합해서 dp[n]이 된다. + +따라서 dp[n] = dp[n-1] + dp[n-2] + dp[n-3]으로 점화식을 만들 수 있다. + +## 보완 + +- DP문제인데 DP로 안풀었다. 😂 +- 도호님 방법 처럼 DP로 풀어볼 필요도 있을듯.. diff --git a/src/grap3fruit/boj/9095.py b/src/grap3fruit/boj/9095.py new file mode 100644 index 0000000..70658a2 --- /dev/null +++ b/src/grap3fruit/boj/9095.py @@ -0,0 +1,25 @@ +import sys + +T = int(sys.stdin.readline()) +N_list = [] +for _ in range(T): + N_list.append(int(sys.stdin.readline())) + +dp = [0]*11 +dp[1] = 1 +dp[2] = 2 +dp[3] = 4 + +for N in N_list: + if N <= 3: + print(dp[N]) + continue + + index = 4 + while True: + dp[index] = dp[index-1] + dp[index-2] + dp[index-3] + if index == N: + print(dp[index]) + break + + index += 1 \ No newline at end of file diff --git a/src/grap3fruit/input_test.py b/src/grap3fruit/input_test.py new file mode 100644 index 0000000..a9472f8 --- /dev/null +++ b/src/grap3fruit/input_test.py @@ -0,0 +1,37 @@ +import sys +from collections import deque +#n, m = map(int,sys.stdin.readline().strip().split()) +#num = list(map(int,sys.stdin.readline().strip().split())) + +# +#datas = list(map(int,sys.stdin.readline().strip().split())) + +#print(num[0]*num[1]) + + +## case ## +# 5 +# 3 2 1 -3 -1 + +n = int(sys.stdin.readline()) +arr = list(map(int,sys.stdin.readline().strip().split())) + + +## case ## +# 1 2 3 4 5 + +num_list = list(map(int, input().split())) + +## case ## +# abcd +# 3 +# P x +# L +# P y + +input_data = sys.stdin.readline().strip() +cmd_count = int(sys.stdin.readline().strip()) +cmd = [] + +for i in range(0, cmd_count): + cmd.append(list(sys.stdin.readline().strip().split())) \ No newline at end of file From 668286e3f5711ee5e4cbac71e944c8eda7f98873 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Sat, 14 Nov 2020 15:01:55 +0900 Subject: [PATCH 108/193] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ed0786e..a9bc09b 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ | 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | | 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평범한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | | 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | +| 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | ## :blue_book: Additional Study From 8366454bdb9b8dbc181f33783d2ebfd638945afb Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 14 Nov 2020 17:23:43 +0900 Subject: [PATCH 109/193] solve : baekjoon 1932 --- src/do02reen24/Review/week11.md | 9 +++++++++ .../dynamic-programming/baekjoon_1932.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 src/do02reen24/Review/week11.md create mode 100644 src/do02reen24/dynamic-programming/baekjoon_1932.py diff --git a/src/do02reen24/Review/week11.md b/src/do02reen24/Review/week11.md new file mode 100644 index 0000000..215bf30 --- /dev/null +++ b/src/do02reen24/Review/week11.md @@ -0,0 +1,9 @@ +# :fire: week11 + +## :ballot_box_with_check: 백준 12731 + +## :ballot_box_with_check: 백준 1932 + +* DB를 적용하여 쉽게 풀 수 있었다. + +## :ballot_box_with_check: 백준 1254 diff --git a/src/do02reen24/dynamic-programming/baekjoon_1932.py b/src/do02reen24/dynamic-programming/baekjoon_1932.py new file mode 100644 index 0000000..16f22f4 --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_1932.py @@ -0,0 +1,16 @@ +import sys + +if __name__ == "__main__": + n = int(sys.stdin.readline()) + triangle = [] + best = [] + for i in range(n): + triangle.append(list(map(int, sys.stdin.readline().rstrip().split(' ')))) + best.append([0] * (i+1)) + best[0][0] = triangle[0][0] + for i in range(1, n): + best[i][0] = triangle[i][0] + best[i-1][0] + for k in range(1, i): + best[i][k] = triangle[i][k] + max(best[i-1][k-1], best[i-1][k]) + best[i][i] = triangle[i][i] + best[i-1][i-1] + print(max(best[n-1])) From cb430be35c13369ada7406c12c456b0ed4c5cdca Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sat, 14 Nov 2020 17:36:19 +0900 Subject: [PATCH 110/193] solve : baekjoon 12731 --- src/do02reen24/Review/week11.md | 8 +++++ src/do02reen24/etc/baekjoon_12731.py | 54 ++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/do02reen24/etc/baekjoon_12731.py diff --git a/src/do02reen24/Review/week11.md b/src/do02reen24/Review/week11.md index 215bf30..14215d2 100644 --- a/src/do02reen24/Review/week11.md +++ b/src/do02reen24/Review/week11.md @@ -2,6 +2,14 @@ ## :ballot_box_with_check: 백준 12731 +첫 제출에서 컴파일 에러가 떴다. + +알고리즘 스터디원님의 도움으로 백준에서 컴파일 에러시 어디서 에러가 났는지 알려준다는 것을 알게되었다. + +![image](https://user-images.githubusercontent.com/50297117/99143310-c57ea900-269f-11eb-82f4-8eee2a33289e.png) + +is로 문자열을 비교해도 되는줄 알았는데 안됨을 알게 되었고 `==` 으로 고쳐 성공할 수 있었다. + ## :ballot_box_with_check: 백준 1932 * DB를 적용하여 쉽게 풀 수 있었다. diff --git a/src/do02reen24/etc/baekjoon_12731.py b/src/do02reen24/etc/baekjoon_12731.py new file mode 100644 index 0000000..17dc125 --- /dev/null +++ b/src/do02reen24/etc/baekjoon_12731.py @@ -0,0 +1,54 @@ +import sys + +def getIntTime(time): + h = int(time[0:2]) * 60 + m = int(time[3:5]) + return h + m + +def changeInt(start, end, time): + return [getIntTime(start), getIntTime(end) + time] + +if __name__ == "__main__": + t = int(sys.stdin.readline()) + for i in range(t): + time = int(sys.stdin.readline()) + na, nb = map(int, sys.stdin.readline().split(' ')) + a_list, b_list = [], [] + for _ in range(na): + start , end = map(str, sys.stdin.readline().rstrip().split(' ')) + a_list.append(changeInt(start, end, time)) + for _ in range(nb): + start , end = map(str, sys.stdin.readline().rstrip().split(' ')) + b_list.append(changeInt(start, end, time)) + a_list.sort() + b_list.sort() + + sol_A, sol_B = 0, 0 + a_train, b_train = [], [] + + while True: + train_type = None + train = None + if a_list and b_list: + if a_list[0] < b_list[0]: train_type = 'a' + else: train_type = 'b' + elif a_list: train_type = 'a' + elif b_list: train_type = 'b' + else: break + + if train_type == 'a': + start, end = a_list.pop(0) + if a_train and a_train[0] <= start: + a_train.pop(0) + else: sol_A += 1 + b_train.append(end) + b_train.sort() + if train_type == 'b': + start, end = b_list.pop(0) + if b_train and b_train[0] <= start: + b_train.pop(0) + else: sol_B += 1 + a_train.append(end) + a_train.sort() + + print("Case #"+str(i+1)+":",sol_A,sol_B) \ No newline at end of file From fce2d89f93740f82545614556f7e5f2256b7b914 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 14 Nov 2020 21:13:19 +0900 Subject: [PATCH 111/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20128?= =?UTF-8?q?65=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 35 +++++++++++++++++++ .../boj_12865.py" | 19 ++++++++++ 2 files changed, 54 insertions(+) create mode 100644 "src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/README.md" create mode 100644 "src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/boj_12865.py" diff --git "a/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/README.md" "b/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/README.md" new file mode 100644 index 0000000..875dcf4 --- /dev/null +++ "b/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/README.md" @@ -0,0 +1,35 @@ +# 평범한 배낭 + +### 최적의 원리 +> 어떤 문제의 입력사례의 최적해가 그 입력사례를 분할한 부분사례에 대한 최적해를 항상 포함하고 있으면, 그 문제에 대하여 최적의 원리가 성립한다. + +### [참고](https://gsmesie692.tistory.com/113) + +1개. 2개. 3개 + +2차원 배열적으로 생각해볼까? + +W V +6 13 +4 8 +3 6 +5 12 + +D[i][k] = i번째 물건까지 사용하여 k 용량의 가방에 물건을 채울때 최대 가치 + +[0, 0, 0, 0, 0, 13, 13] +[0, 0, 0, 8, 8, 13, 13] +[0, 0, 6, 8, 8, 13, 14] +[0, 0, 6, 8, 12, 13, 14] + +이 문제를 봤을 때 D[i][j] = V[i] + D[i-1][j-w[i]]의 점화식이 적용된다. +여기서 j는 현재 검사하는 배낭의 무게 w[i]는 i의 무게이다. +현재 검사하는 배낭의 무게 - 넣으려고하는 것의 무게를 빼면 +지금까지 알아온 배낭 배열에서 그 무게에 해당하는 값이 최적이므로 +검사 대상이다. + +결국 +w[i] > j D[i][j] = D[i-1][j] +w[i] <= j D[i][j] = max(V[i] + D[i-1][j-w[i]] , D[i-1][j]) + +하면 된다. \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/boj_12865.py" "b/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/boj_12865.py" new file mode 100644 index 0000000..48e38aa --- /dev/null +++ "b/src/Do-ho/dp/boj_12865_\355\217\211\353\262\224\355\225\234\353\260\260\353\202\255/boj_12865.py" @@ -0,0 +1,19 @@ +# w[i] > j D[i][j] = D[i-1][j] +# w[i] <= j D[i][j] = max(V[i] + D[i-1][j-w[i]] , D[i-1][j]) + +import sys + +[N, K] = map(int, sys.stdin.readline().strip().split()) + +B = [] +D = [[0 for _ in range(K)] for _ in range(N)] + +for _ in range(N): + B.append(list(map(int, sys.stdin.readline().strip().split()))) + +for i in range(N): + if i==1: + D[i][B[0][0]] = B[0][1] + continue + for j in range(K): + \ No newline at end of file From 8ff58143afea66013904a691c320b73d39bb4efc Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 14 Nov 2020 21:13:52 +0900 Subject: [PATCH 112/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20127?= =?UTF-8?q?31=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - datetime을 통한 풀이 --- .../README.md" | 17 ++++++ .../boj_12731.py" | 56 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 "src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/README.md" create mode 100644 "src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/boj_12731.py" diff --git "a/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/README.md" "b/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/README.md" new file mode 100644 index 0000000..203fee3 --- /dev/null +++ "b/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/README.md" @@ -0,0 +1,17 @@ +# 열차 시간표(Small) + +test case + +``` +1 +0 +2 2 +10:30 11:00 +12:00 13:00 +11:00 12:00 +09:00 10:30 +``` +``` 0, 1 ``` + +A와 B를 시간 순으로 정렬하고 제일 앞 기차를 출발 시켜서 +계속적으로 검사해나감 \ No newline at end of file diff --git "a/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/boj_12731.py" "b/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/boj_12731.py" new file mode 100644 index 0000000..a2b2cc4 --- /dev/null +++ "b/src/Do-ho/implementation/boj_12731_\354\227\264\354\260\250\354\213\234\352\260\204\355\221\234small/boj_12731.py" @@ -0,0 +1,56 @@ +import sys +from datetime import datetime, timedelta + +def trainInput(n, result, alpha): + for _ in range(n): + [inputStartTime, inputEndTime] = list(sys.stdin.readline().strip().split()) + startTime = list(map(int, inputStartTime.split(':'))) + endTime = list(map(int, inputEndTime.split(':'))) + + start = datetime(2020, 11, 14, startTime[0], startTime[1]) + end = datetime(2020, 11, 14, endTime[0], endTime[1]) + + result.append([start, end, alpha, True]) + +def trainsInput(NA, NB): + result = [] + trainInput(NA, result, 'A') + trainInput(NB, result, 'B') + + result.sort() + return result + +def getStartTrains(L, T): + S = {"A": 0, "B": 0} + Ttime = timedelta(minutes=T) + + for i, trainTime in enumerate(L): + if not trainTime[3]: continue + trainTime[3] = False + S[trainTime[2]] += 1 + + checkTime = trainTime[1] + Ttime + checkStation = trainTime[2] + + for j in range(i+1, len(L)): + if L[j][3] and checkTime <= L[j][0] and checkStation != L[j][2]: + L[j][3] = False + checkTime = L[j][1] + Ttime + checkStation = L[j][2] + + return [S["A"], S["B"]] + +def case(caseID): + T = int(sys.stdin.readline()) + [NA, NB] = list(map(int, sys.stdin.readline().strip().split())) + L = trainsInput(NA, NB) + [SA, SB] = getStartTrains(L, T) + + sys.stdout.write("Case #" + str(caseID) +": " + str(SA) + " " + str(SB) + "\n") + + +# 테스트 케이스 개수 N +N = int(sys.stdin.readline()) + +for i in range(1, N+1): + case(i) \ No newline at end of file From c9ba10631d0eace118d4785ec7bb5225ab37af99 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 14 Nov 2020 21:53:10 +0900 Subject: [PATCH 113/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20193?= =?UTF-8?q?2=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - DP를 통한 풀이 --- .../README.md" | 5 +++++ .../boj_1932.py" | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 "src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/README.md" create mode 100644 "src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/boj_1932.py" diff --git "a/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/README.md" "b/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/README.md" new file mode 100644 index 0000000..c6b31ea --- /dev/null +++ "b/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/README.md" @@ -0,0 +1,5 @@ +# 정수삼각형 + +D에 저장하면서 밑으로 내려감 + +맨 왼쪽에 대해서만 예외처리를 해주면 좋을듯 \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/boj_1932.py" "b/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/boj_1932.py" new file mode 100644 index 0000000..3a8f9d9 --- /dev/null +++ "b/src/Do-ho/dp/boj_1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/boj_1932.py" @@ -0,0 +1,22 @@ +import sys + +n = int(sys.stdin.readline()) + +D = [[0 for _ in range(n)] for _ in range(n)] + +def f(idx): + return 0 + +triangle = [] + +for i in range(n): + triangle.append(list(map(int, sys.stdin.readline().strip().split()))) + +D[0][0] = triangle[0][0] + +for i in range(1, n): + for j in range(i+1): + try: D[i][j] = triangle[i][j] + max(D[i-1][j-1], D[i-1][j]) + except: D[i][j] = triangle[i][j] + D[i-1][j] + +print(max(D[n-1])) \ No newline at end of file From c86b1c9546571af47af7d3e406eb9b33efb7439e Mon Sep 17 00:00:00 2001 From: Do-ho Date: Sat, 14 Nov 2020 22:35:36 +0900 Subject: [PATCH 114/193] =?UTF-8?q?Add:=20solve=20=EB=B0=B1=EC=A4=80=20125?= =?UTF-8?q?4=20=EB=AC=B8=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 팰린드롬 풀이 --- .../README.md" | 9 +++++++++ .../boj_1254.py" | 14 ++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 "src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/README.md" create mode 100644 "src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/boj_1254.py" diff --git "a/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/README.md" "b/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/README.md" new file mode 100644 index 0000000..d560de4 --- /dev/null +++ "b/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/README.md" @@ -0,0 +1,9 @@ +# 팰린드롬 만들기 + +팰린드롬 만들기 + +뒤부터 최대의 팰린드롬을 찾고 그 나머지 length를 더한다. + +=== + +뒤부터 최대의 팰린드롬을 찾고 그 길이를 2배한 거에서 뺀다. \ No newline at end of file diff --git "a/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/boj_1254.py" "b/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/boj_1254.py" new file mode 100644 index 0000000..8a138d2 --- /dev/null +++ "b/src/Do-ho/implementation/boj_1254_\355\214\260\353\246\260\353\223\234\353\241\254\353\247\214\353\223\244\352\270\260/boj_1254.py" @@ -0,0 +1,14 @@ +import sys + +def palindrome(S): + return S == S[::-1] + +S = sys.stdin.readline().strip() +S_reverse = S[::-1] + +max_palindrome = 0 +for i in range(len(S_reverse)): + checkString = S_reverse[0:i+1] + if palindrome(checkString): max_palindrome = len(checkString) + +print(len(S)*2 - max_palindrome) \ No newline at end of file From f6454c954d8ac149b690b516a6bd2759d1bbee7f Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sun, 15 Nov 2020 11:41:24 +0900 Subject: [PATCH 115/193] =?UTF-8?q?week=2011=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EB=B0=8F=20=EB=AC=B8=EC=84=9C=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/boj/1254.md | 45 ++++++++++++++ src/grap3fruit/boj/1254.py | 50 ++++++++++++++++ src/grap3fruit/boj/12731.md | 114 ++++++++++++++++++++++++++++++++++++ src/grap3fruit/boj/12731.py | 71 ++++++++++++++++++++++ src/grap3fruit/boj/1932.md | 48 +++++++++++++++ src/grap3fruit/boj/1932.py | 56 ++++++++++++++++++ 6 files changed, 384 insertions(+) create mode 100644 src/grap3fruit/boj/1254.md create mode 100644 src/grap3fruit/boj/1254.py create mode 100644 src/grap3fruit/boj/12731.md create mode 100644 src/grap3fruit/boj/12731.py create mode 100644 src/grap3fruit/boj/1932.md create mode 100644 src/grap3fruit/boj/1932.py diff --git a/src/grap3fruit/boj/1254.md b/src/grap3fruit/boj/1254.md new file mode 100644 index 0000000..9428bf6 --- /dev/null +++ b/src/grap3fruit/boj/1254.md @@ -0,0 +1,45 @@ +# 1254 - 성공 + +## 팰린드롬 + +abbca 라고 하면, + +마지막 a를 기준으로 맨 앞에서 부터 넣어서 팰린드롬 체크를 한다. + +``` +abbca a + +abbca ba + +abbca bba + +abbc a cbba +``` + +이렇게 맨 앞 요소부터 차례대로 넣어주면 된다. + +뒤에서 i번째 자리에 data[i]를 넣게 된다. + +뒤에서 i번째 자리에 어떻게 넣어줄까? + +deque 사용해서 해결 + +add_string에 appendleft를 해서 + +원본 data + add_string 한것을 팰린드롬 체크 해서 돌려준다. + +``` +data | add_string + +abbca a + +abbca ba + +abbca bba + +abbca cbba → 팰린드롬! +``` + +### 이슈 + +- deque 안쓰고도 할 수 있을것 같은데,, 좀 더 예쁜 방법으로? diff --git a/src/grap3fruit/boj/1254.py b/src/grap3fruit/boj/1254.py new file mode 100644 index 0000000..44d0eed --- /dev/null +++ b/src/grap3fruit/boj/1254.py @@ -0,0 +1,50 @@ +import sys +from collections import deque + +data = sys.stdin.readline().strip() + +def checkPD(data): + N = len(data) + + if N % 2 == 0: + if data[int(N/2)] != data[int(N/2)-1] : + return False + + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + return False + + return True + + if N % 2 == 1: + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + return False + + return True + +# print(checkPD(['a','b','b','c','a'])) + +# deq = deque(['a','b','c','b', 'a']) +# print(checkPD(deq)) + +def calc(data): + N = len(data) + if N == 1: + print(1) + return + + count = N + add_string = deque([]) + for i in range(0, N): + PD = deque(data) + PD.extend(add_string) + + if checkPD(PD): + print(count, PD) + return + + add_string.appendleft(data[i]) + count += 1 + +calc(data) \ No newline at end of file diff --git a/src/grap3fruit/boj/12731.md b/src/grap3fruit/boj/12731.md new file mode 100644 index 0000000..bf51add --- /dev/null +++ b/src/grap3fruit/boj/12731.md @@ -0,0 +1,114 @@ +# 12731 - 성공(힌트) + +## 시간 계산 문제 + +### 알고리즘 + +일단 시 → 분으로 변경 + +60 \* hour + min + +main 함수에서 분으로 된 2차원 배열 만듬. + +na_arr = [[660, 720], [960, 1080]] + +nb_arr = [[720, 960], [540, 660]] ..이런식 + +calc 함수에 (na_arr, nb_arr, T(=회차시간)) 파라미터 넘겨줘서, + +NA를 돌면서 NA_min - T 보다 NB_max 가 작거나 같은게 있으면, 해당 nb를 제거. + +NB도 똑같이 진행. + +위 if에 들어갈때 count -= 1 해서 na, nb 각각 카운트 리턴. + +### 테스트 케이스 + +``` +1 +5 +1 2 +09:00 11:00 +13:00 15:00 +14:00 16:00 + +Case #1: 1 1 + +1 +5 +2 1 +13:00 15:00 +14:00 16:00 +09:00 11:00 + +Case #1: 1 1 + +1 +0 +1 2 +09:00 11:00 +11:00 12:00 +12:00 16:00 + +Case #1: 1 1 + + +1 +0 +0 3 +09:00 11:00 +11:00 12:00 +12:00 16:00 + +Case #1: 0 3 + + +1 +0 +0 3 +09:00 11:00 +11:00 12:00 +12:00 16:00 + +Case #1: 0 3 + + +1 +1 +1 2 +09:00 11:00 +11:00 12:00 +12:00 16:00 + +Case #1: 1 1 + +1 +0 +2 2 +12:00 16:00 +11:00 12:00 +16:00 18:00 +09:00 11:00 + +Case #1: 1 1 + +1 +0 +2 2 +11:00 12:00 +16:00 18:00 +12:00 16:00 +09:00 11:00 + +Case #1: 0 1 +``` + +### 이슈 + +- 테케 많이 돌렸는데, 통과가 안된다 😭 +- 도연님꺼 참고해서, sort넣었더니 통과됨. +- sort 안해주면 늦은 시간껄 먼저 가져가버려서 꼬이는 경우가 생기는듯 하다. + +### 보완 + +- 다시 풀어보자.. diff --git a/src/grap3fruit/boj/12731.py b/src/grap3fruit/boj/12731.py new file mode 100644 index 0000000..fcaf0b9 --- /dev/null +++ b/src/grap3fruit/boj/12731.py @@ -0,0 +1,71 @@ +import sys +import copy + +def getMinValueFromStr(time_str = "12:35"): + hour = int(time_str[0]+time_str[1]) + min = int(time_str[3]+time_str[4]) + return hour*60 + min + +def calc(backup_na, backup_nb, T): + print("check1: ", backup_na, backup_nb) + na_arr = copy.deepcopy(backup_na) + nb_arr = copy.deepcopy(backup_nb) + + count_na = len(backup_na) + count_nb = len(backup_nb) + for na_el in na_arr : # NA가 먼저 돌때, NB해당되는게있으면, + min = na_el[0] - T # NA[1] 응 내가 먼저 NB 가져갈게~ 해서 NB 빼줘야함. 다음 NA들이 착각 안하도록 ㅇㅇ + for nb_el in nb_arr: + print("na_el:",na_el[0]," nb_el:", nb_el[1]) + if min >= nb_el[1] : + nb_arr.remove(nb_el) + count_na -= 1 + break + + na_arr = backup_na + nb_arr = backup_nb + for nb_el in nb_arr : + min = nb_el[0] - T + for na_el in na_arr: + if min >= na_el[1] : + na_arr.remove(na_el) + count_nb -= 1 + break + + return [count_na, count_nb] + + +def main(): + N = int(sys.stdin.readline()) + + for x in range(N): + T = int(sys.stdin.readline()) # 회차시간 + NA, NB = list(map(int,sys.stdin.readline().strip().split())) + + na_arr = [] + nb_arr = [] + + for i in range(NA): + temp_arr = list(map(str,sys.stdin.readline().strip().split())) + min = getMinValueFromStr(temp_arr[0]) + max = getMinValueFromStr(temp_arr[1]) + na_arr.append([min,max]) + print(i, min, max) + + for i in range(NB): + temp_arr = list(map(str,sys.stdin.readline().strip().split())) + min = getMinValueFromStr(temp_arr[0]) + max = getMinValueFromStr(temp_arr[1]) + nb_arr.append([min,max]) + print(i, min, max) + + print(NA,NB) + print(na_arr, nb_arr) + na_arr.sort() + nb_arr.sort() + + result_NA, result_NB = calc(na_arr, nb_arr, T) + + print("Case #{}:".format(x+1), result_NA, result_NB) + +main() diff --git a/src/grap3fruit/boj/1932.md b/src/grap3fruit/boj/1932.md new file mode 100644 index 0000000..729a9ea --- /dev/null +++ b/src/grap3fruit/boj/1932.md @@ -0,0 +1,48 @@ +# 1932 - 성공 + +## DP + +삼각형 + +```python +i=0 0 +i=1 1 2 +i=2 3 4 5 +i=3 6 7 8 9 + +i 값과, a_index값(위 삼각형의 숫자값이 a_index)을 활용 +``` + +data에 입력을 담고, + +a에 평탄화된 data를 담음. ([1],[2,3]) → ([1,2,3]) + +base dp : dp[0], dp[1], dp[2] 구해놓고. + +dp[n]에서 n이 삼각형 한 row의 맨 앞일 경우 + +```python +dp[a_index] = dp[a_index-i] + a[a_index] +``` + +dp[n]에서 n이 삼각형 한 row의 맨 뒤일 경우 + +```python +dp[a_index] = dp[a_index-i-1] + a[a_index] +``` + +dp[n]에서 n이 삼각형 한 row의 맨앞 또는 맨 뒤가 아닌, 중간일 경우 + +```python +dp[a_index] = max(dp[a_index-i-1] + a[a_index], dp[a_index-i] + a[a_index]) +``` + +이때 dp의 최대값을 출력해주면 된다. + +### 이슈 + +- 전형적인 DP문제. 근데 계산이 조금 복합해서 오래걸렸음. + +### 보완 + +- 더 많이 풀자 diff --git a/src/grap3fruit/boj/1932.py b/src/grap3fruit/boj/1932.py new file mode 100644 index 0000000..bdd0222 --- /dev/null +++ b/src/grap3fruit/boj/1932.py @@ -0,0 +1,56 @@ +import sys +import itertools +N = int(sys.stdin.readline()) + +data = [] +for _ in range(N): + data.append(list(map(int,sys.stdin.readline().strip().split()))) + +print("data:",data) + +def chain(*iterables): # 참조 : https://winterj.me/list_of_lists_to_flatten/ + # chain('ABC', 'DEF') --> A B C D E F + for it in iterables: + for element in it: + yield element + +a = list(itertools.chain(*data)) +print("a:",a) + +def calc(data, a): + + dp = [0]*501 + dp[0] = a[0] + + if N == 1: + return (dp[0]) + + + dp[1] = a[0] + a[1] + dp[2] = a[0] + a[2] + + if N == 2: + return max(dp[1], dp[2]) + + a_index = 0 + + for i, row in enumerate(data) : + print(i) + if i == 0: + continue + + for j, el in enumerate(row): + a_index += 1 + if j == 0 : + dp[a_index] = dp[a_index-i] + a[a_index] + continue + + if j == len(row)-1: + dp[a_index] = dp[a_index-i-1] + a[a_index] + continue + + dp[a_index] = max(dp[a_index-i-1] + a[a_index], dp[a_index-i]+a[a_index]) + + return(max(dp)) + +print(calc(data ,a)) \ No newline at end of file From ac0e56cb9e78df5d71003040f7e1b74e1df63592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 15 Nov 2020 20:08:08 +0900 Subject: [PATCH 116/193] boj 1254 --- .../Main.java" | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 "src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" diff --git "a/src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" "b/src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" new file mode 100644 index 0000000..6a03965 --- /dev/null +++ "b/src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" @@ -0,0 +1,33 @@ +package boj1254_팰린드롬; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Main { + + static String S; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + S = br.readLine(); + int ans = 0; + + for (int i = 0; i < S.length(); i++) { + if (checkPalindrome(S, i)) { + ans = S.length() + i; + break; + } + } + System.out.println(ans); + + } + + static boolean checkPalindrome(String s, int start) { + int end = s.length() - 1; + for (int i = start; i <= end; i++) { + if (s.charAt(i) != s.charAt(end + start - i)) return false; + } + return true; + } +} From 48fd9240e153007b63d6d9dfa8019993f5d7c0b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 15 Nov 2020 20:08:25 +0900 Subject: [PATCH 117/193] boj 1932 --- .../Main.java" | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 "src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" diff --git "a/src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" "b/src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" new file mode 100644 index 0000000..5c7d5ad --- /dev/null +++ "b/src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" @@ -0,0 +1,43 @@ +package boj1932_정수삼각형; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + final static int MAX = 500; + static int n; + static int tri[][] = new int[MAX + 1][MAX + 1]; + static int d[][] = new int[MAX + 1][MAX + 1]; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + n = Integer.parseInt(br.readLine()); + for (int i = 1; i <= n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 1; j <= i; j++) { + tri[i][j] = Integer.parseInt(st.nextToken()); + } + } + + d[1][1] = tri[1][1]; + + for (int i = 2; i <= n; i++) { + for (int j = 1; j <= n; j++) { + d[i][j] = Math.max(d[i - 1][j - 1], d[i - 1][j]) + tri[i][j]; + } + } + + int ans = 0; + + for (int i = 1; i <= n; i++) { + ans = Math.max(ans, d[n][i]); + } + + System.out.println(ans); + } + +} From c7f2e41d53754b60a0c2fb0fcc5f8fdf0b30ade5 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 24 Dec 2020 03:49:33 +0900 Subject: [PATCH 118/193] solve: boj 11399 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 단순 Greedy 문제로 sort를 이용한 해결 --- src/Do-ho/greedy/boj_11399_ATM/README.md | 27 +++++++++++++++++++++ src/Do-ho/greedy/boj_11399_ATM/boj_11399.py | 15 ++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/Do-ho/greedy/boj_11399_ATM/README.md create mode 100644 src/Do-ho/greedy/boj_11399_ATM/boj_11399.py diff --git a/src/Do-ho/greedy/boj_11399_ATM/README.md b/src/Do-ho/greedy/boj_11399_ATM/README.md new file mode 100644 index 0000000..3b8b2ed --- /dev/null +++ b/src/Do-ho/greedy/boj_11399_ATM/README.md @@ -0,0 +1,27 @@ +# ATM + +case +``` 3 1 4 3 2 ``` + +3 +3 + 1 = 4 +3 + 1 + 4 = 8 +3 + 1 + 4 + 3 = 11 +3 + 1 + 4 + 3 + 2 = 13 + +3 + 4 + 8 + 11 + 13 = 39 + +------- + +case +``` 1 2 3 3 4 ``` + +1 +1 + 2 = 3 +1 + 2 + 3 = 6 +1 + 2 + 3 + 3 = 9 +1 + 2 + 3 + 3 + 4 = 13 + +1 + 3 + 6 + 9 + 13 = 32 + +sort()한게 제일 좋다! \ No newline at end of file diff --git a/src/Do-ho/greedy/boj_11399_ATM/boj_11399.py b/src/Do-ho/greedy/boj_11399_ATM/boj_11399.py new file mode 100644 index 0000000..797a2dd --- /dev/null +++ b/src/Do-ho/greedy/boj_11399_ATM/boj_11399.py @@ -0,0 +1,15 @@ +import sys + +N = int(sys.stdin.readline()) +P = list(map(int, sys.stdin.readline().strip().split())) + +P.sort() + +Psum = 0 +offset = 0 + +for item in P: + offset += item + Psum += offset + +sys.stdout.write(str(Psum) + '\n') \ No newline at end of file From ffb53d55a12e1a5eb7e9a506bbc5e3ed07009620 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 24 Dec 2020 04:31:54 +0900 Subject: [PATCH 119/193] solve: boj 17609 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 양쪽부터 차근차근 비교해나가며 성공 --- .../README.md" | 90 +++++++++++++++++++ .../boj_17609.py" | 29 ++++++ 2 files changed, 119 insertions(+) create mode 100644 "src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/README.md" create mode 100644 "src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/boj_17609.py" diff --git "a/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/README.md" "b/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/README.md" new file mode 100644 index 0000000..7b35e21 --- /dev/null +++ "b/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/README.md" @@ -0,0 +1,90 @@ +# 회문 + +### 시간초과... + +``` +import sys + +def isPalindrome(S): + return S == S[::-1] + +def isPseudoPalindrome(S): + for i in range(len(S)): + if(isPalindrome(S[:i] + S[i+1:])): return True + return False + +def palindrome(S): + if(isPalindrome(S)): return '0' + elif(isPseudoPalindrome(S)): return '1' + return '2' + +T = int(sys.stdin.readline()) + +for _ in range(T): + S = sys.stdin.readline().strip() + sys.stdout.write(palindrome(S) + '\n') +``` + +### 시간초과 2.. + +``` +import sys + +def isPalindrome(S): + mid = int(len(S) / 2) + for i in range(mid): + if (S[i] != S[len(S)-1-i]): return False + return True + +def isPseudoPalindrome(S): + for i in range(len(S)): + if(isPalindrome(S[:i] + S[i+1:])): return True + return False + +def palindrome(S): + if(isPalindrome(S)): return '0' + elif(isPseudoPalindrome(S)): return '1' + return '2' + +T = int(sys.stdin.readline()) + +for _ in range(T): + S = sys.stdin.readline().strip() + + sys.stdout.write(palindrome(S) + '\n') +``` + +### 성공 + +``` +import sys + +def isPalindrome(S): + mid = int(len(S) / 2) + for i in range(mid): + if (S[i] != S[len(S)-1-i]): return False + return True + +def isPseudoPalindrome(S): + mid = int(len(S) / 2) + for i in range(mid): + if (S[i] != S[len(S)-1-i]): + FrontStr = S[:i] + S[i+1:] + BackStr = S[:len(S)-1-i] + S[len(S)-i:] + if(isPalindrome(FrontStr) or isPalindrome(BackStr)): return True + return False + return True + +def palindrome(S): + if(isPalindrome(S)): return '0' + elif(isPseudoPalindrome(S)): return '1' + return '2' + +if __name__ == '__main__': + T = int(sys.stdin.readline()) + + for _ in range(T): + S = sys.stdin.readline().strip() + sys.stdout.write(palindrome(S) + '\n') +``` + diff --git "a/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/boj_17609.py" "b/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/boj_17609.py" new file mode 100644 index 0000000..4583ebc --- /dev/null +++ "b/src/Do-ho/greedy/boj_17609_\355\232\214\353\254\270/boj_17609.py" @@ -0,0 +1,29 @@ +import sys + +def isPalindrome(S): + mid = int(len(S) / 2) + for i in range(mid): + if (S[i] != S[len(S)-1-i]): return False + return True + +def isPseudoPalindrome(S): + mid = int(len(S) / 2) + for i in range(mid): + if (S[i] != S[len(S)-1-i]): + FrontStr = S[:i] + S[i+1:] + BackStr = S[:len(S)-1-i] + S[len(S)-i:] + if(isPalindrome(FrontStr) or isPalindrome(BackStr)): return True + return False + return True + +def palindrome(S): + if(isPalindrome(S)): return '0' + elif(isPseudoPalindrome(S)): return '1' + return '2' + +if __name__ == '__main__': + T = int(sys.stdin.readline()) + + for _ in range(T): + S = sys.stdin.readline().strip() + sys.stdout.write(palindrome(S) + '\n') \ No newline at end of file From 9ad09ad709a028c8fb952a70d564cd7bfb2cb6b8 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 24 Dec 2020 09:04:33 +0900 Subject: [PATCH 120/193] solve : baekjoon 11399 --- src/do02reen24/Review/week12.md | 7 +++++ src/do02reen24/Review/week9.md | 34 ++++++++++++++++++++++++- src/do02reen24/greedy/baekjoon_11399.py | 13 ++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/do02reen24/Review/week12.md create mode 100644 src/do02reen24/greedy/baekjoon_11399.py diff --git a/src/do02reen24/Review/week12.md b/src/do02reen24/Review/week12.md new file mode 100644 index 0000000..dd79b70 --- /dev/null +++ b/src/do02reen24/Review/week12.md @@ -0,0 +1,7 @@ +# :fire: week12 + +## :ballot_box_with_check: 백준 11399 + +- 시간순으로 정렬하여 쉽게 풀 수 있었다. + +## :ballot_box_with_check: 백준 17609 diff --git a/src/do02reen24/Review/week9.md b/src/do02reen24/Review/week9.md index 52ed3ef..1fb0955 100644 --- a/src/do02reen24/Review/week9.md +++ b/src/do02reen24/Review/week9.md @@ -1,4 +1,4 @@ -# :fire: week8 +# :fire: week9 주제 : Dynamic programming @@ -42,3 +42,35 @@ int main() { - 나누기는 성립하지 않는다. ## :ballot_box_with_check: 백준 12865 + +#### 시간초과 + +```python +import sys + +def pickObject(index, sumW, sumV, isPick): + global backpack, ans + if index >= n: return + if sumW > k: return + if sumW <= k and sumV > ans: ans = sumV + w = 0 + v = 0 + if isPick: + w, v = backpack[index] + pickObject(index + 1, sumW + w, sumV + v, True) + pickObject(index + 1, sumW + w, sumV + v, False) + +n, k = map(int, sys.stdin.readline().split(' ')) +ans = 0 +backpack = [] +for _ in range(n): + w, v = map(int, sys.stdin.readline().split(' ')) + backpack.append((w, v)) + +pickObject(0, 0, 0, True) +pickObject(0, 0, 0, False) + +print(ans) +``` + +- 재귀로 풀지 않고 논리적인 생각을 통해 앞의 결과 중 더 큰 것을 골라야함을 알았다. diff --git a/src/do02reen24/greedy/baekjoon_11399.py b/src/do02reen24/greedy/baekjoon_11399.py new file mode 100644 index 0000000..7942bb5 --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_11399.py @@ -0,0 +1,13 @@ +import sys + +n = int(sys.stdin.readline()) +p = list(map(int, sys.stdin.readline().split())) +p.sort() + +ans = 0 +waitSum = 0 + +for num in p: + waitSum = waitSum + num + ans = ans + waitSum +print(ans) From 7880bd405eff4d37041e548de1e155a31e9dde9f Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 24 Dec 2020 09:29:04 +0900 Subject: [PATCH 121/193] solve : baekjoon 17609 --- src/do02reen24/Review/week12.md | 10 +++++++++ src/do02reen24/greedy/baekjoon_17609.py | 27 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/do02reen24/greedy/baekjoon_17609.py diff --git a/src/do02reen24/Review/week12.md b/src/do02reen24/Review/week12.md index dd79b70..32a6e44 100644 --- a/src/do02reen24/Review/week12.md +++ b/src/do02reen24/Review/week12.md @@ -5,3 +5,13 @@ - 시간순으로 정렬하여 쉽게 풀 수 있었다. ## :ballot_box_with_check: 백준 17609 + +1. 우선 펠린드롬인지 확인한다. + - 맞다면 0을 반환한다. + - 아니라면 펠린드롬을 깨지게 만든 index를 반환하고 다음 단계로 넘어간다. +2. 왼쪽 단어(index)를 하나 삭제하여 펠린드롬인지 확인한다. + - 맞다면 1을 반환한다. + - 아니라면 다음 단계로 넘어간다. +3. 오른쪽 단어(length-index)를 하나 삭제하여 펠린드롬인지 확인한다. + - 맞다면 1을 반환한다. + - 아니라면 2를 반환한다. diff --git a/src/do02reen24/greedy/baekjoon_17609.py b/src/do02reen24/greedy/baekjoon_17609.py new file mode 100644 index 0000000..59c7065 --- /dev/null +++ b/src/do02reen24/greedy/baekjoon_17609.py @@ -0,0 +1,27 @@ +import sys + +def getPalindrome(word, length): + index = 0 + while length - index > index: + if word[index] == word[length - index]: + index = index + 1 + continue + return index + return -1 + +def isPalindrome(word, length): + index = getPalindrome(word, length) + if index == -1: return 0 + + deleteLeft = word[:index] + word[index+1:] + if getPalindrome(deleteLeft, len(deleteLeft) - 1) == -1: return 1 + + deleteRight = word[:length - index] + word[length - index+1:] + if getPalindrome(deleteRight, len(deleteRight) - 1) == -1: return 1 + + return 2 + +n = int(sys.stdin.readline()) +for _ in range(n): + word = sys.stdin.readline().rstrip() + print(isPalindrome(word, len(word) - 1)) From 2d81d58ae7e138b791d9e91e9c2c16ed0dce5dd4 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 24 Dec 2020 16:11:30 +0900 Subject: [PATCH 122/193] solve : baekjoon 1254 --- src/do02reen24/Review/week11.md | 5 ++++- src/do02reen24/brute-force/baekjoon_1254.py | 22 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/do02reen24/brute-force/baekjoon_1254.py diff --git a/src/do02reen24/Review/week11.md b/src/do02reen24/Review/week11.md index 14215d2..67a39b8 100644 --- a/src/do02reen24/Review/week11.md +++ b/src/do02reen24/Review/week11.md @@ -12,6 +12,9 @@ is로 문자열을 비교해도 되는줄 알았는데 안됨을 알게 되었 ## :ballot_box_with_check: 백준 1932 -* DB를 적용하여 쉽게 풀 수 있었다. +- DB를 적용하여 쉽게 풀 수 있었다. ## :ballot_box_with_check: 백준 1254 + +- 처음 11주차 때는 각 경우별로 고려해주는 코드를 짜다가 꼬여서 풀지 못했었다. 12주차의 회문문제를 풀고 팰린드롬 문제에 다시 도전하였다. +- 회문 문제를 풀 때처럼 팰린드롬인지 체크해주는 함수를 구현하여 조건에 맞지 않으면 정답의 길이를 늘려주며 다시 검사를 진행하는 방식으로 구현하였다. diff --git a/src/do02reen24/brute-force/baekjoon_1254.py b/src/do02reen24/brute-force/baekjoon_1254.py new file mode 100644 index 0000000..7a68939 --- /dev/null +++ b/src/do02reen24/brute-force/baekjoon_1254.py @@ -0,0 +1,22 @@ +import sys + +def isPalindrome(word, start, end): + index = 0 + while end - index > start + index: + if word[end-index] == word[start+index]: + index = index + 1 + continue + return False + return True + + +word = sys.stdin.readline().rstrip() +ans = len(word) +start, end = 0, len(word) - 1 + +while True: + if isPalindrome(word, start, end): break + ans = ans + 1 + start = start + 1 + +print(ans) From c256268737a3451efe7251ff81ed43af7a72cfcf Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 24 Dec 2020 16:25:27 +0900 Subject: [PATCH 123/193] solve : baekjoon 1149 --- src/do02reen24/Review/week10.md | 2 ++ .../dynamic-programming/baekjoon_1149.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 src/do02reen24/dynamic-programming/baekjoon_1149.py diff --git a/src/do02reen24/Review/week10.md b/src/do02reen24/Review/week10.md index b51a4d2..9e9dc1f 100644 --- a/src/do02reen24/Review/week10.md +++ b/src/do02reen24/Review/week10.md @@ -9,3 +9,5 @@ ## :ballot_box_with_check: 백준 2579 ## :ballot_box_with_check: 백준 1149 + +- 문제가 dynamic-programming인 것을 고려하여 각 r, g, b에 대해 최소값을 누적하여 관리하는 리스트를 생성하여 해결하였다. diff --git a/src/do02reen24/dynamic-programming/baekjoon_1149.py b/src/do02reen24/dynamic-programming/baekjoon_1149.py new file mode 100644 index 0000000..f8039f3 --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_1149.py @@ -0,0 +1,17 @@ +import sys + +n = int(sys.stdin.readline()) +RGB = [] +for _ in range(n): + r, g, b = map(int, sys.stdin.readline().split()) + RGB.append((r, g, b)) + +r_cost, g_cost, b_cost = [0], [0], [0] + +for i in range(0, n): + r, g, b = RGB[i] + r_cost.append(r + min(g_cost[i], b_cost[i])) + g_cost.append(g + min(r_cost[i], b_cost[i])) + b_cost.append(b + min(r_cost[i], g_cost[i])) + +print(min(r_cost[n],g_cost[n],b_cost[n])) From 777584009c53d3dfff8532d327023fa4bcd931bb Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 25 Dec 2020 01:22:59 +0900 Subject: [PATCH 124/193] solve : baekjoon 2579 --- src/do02reen24/Review/week10.md | 3 +++ .../dynamic-programming/baekjoon_2579.py | 16 ++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 src/do02reen24/dynamic-programming/baekjoon_2579.py diff --git a/src/do02reen24/Review/week10.md b/src/do02reen24/Review/week10.md index 9e9dc1f..89f6d76 100644 --- a/src/do02reen24/Review/week10.md +++ b/src/do02reen24/Review/week10.md @@ -8,6 +8,9 @@ ## :ballot_box_with_check: 백준 2579 +- 마지막 칸에 도착하는 방법은 두가지가 있다. i-2, i-1, i번째 칸에 대해 oxo, xoo 로 선택하는 것이다. +- 각 경우 중 더 큰 값을 선택하며 다음칸으로 넘어가도록 구현하였다. + ## :ballot_box_with_check: 백준 1149 - 문제가 dynamic-programming인 것을 고려하여 각 r, g, b에 대해 최소값을 누적하여 관리하는 리스트를 생성하여 해결하였다. diff --git a/src/do02reen24/dynamic-programming/baekjoon_2579.py b/src/do02reen24/dynamic-programming/baekjoon_2579.py new file mode 100644 index 0000000..8987553 --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_2579.py @@ -0,0 +1,16 @@ +import sys + +def sol(): + n = int(sys.stdin.readline()) + score = [] + for _ in range(n): + score.append(int(sys.stdin.readline())) + + if n <= 2: return sum(score) + + scoreSum = [score[0], score[0]+score[1], max(score[0],score[1])+score[2]] + for i in range(3, n): + scoreSum.append(score[i]+max(score[i-1]+scoreSum[i-3], scoreSum[i-2])) + return scoreSum.pop() + +print(sol()) \ No newline at end of file From 6f18be4792c0f8090b5bd36459691d9ef26cac96 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 25 Dec 2020 01:45:40 +0900 Subject: [PATCH 125/193] =?UTF-8?q?docs=20:=20=EB=AA=BB=ED=91=BC=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20md=20=ED=8C=8C=EC=9D=BC=20=EC=83=9D=EC=84=B1=20-=20?= =?UTF-8?q?=EC=A7=80=EA=B8=88=EA=B9=8C=EC=A7=80=20=ED=92=80=EC=A7=80=20?= =?UTF-8?q?=EB=AA=BB=ED=95=9C=20=EB=AC=B8=EC=A0=9C=EB=93=A4=EC=9D=84=20?= =?UTF-8?q?=EC=A0=95=EB=A6=AC=ED=95=B4=EB=91=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/unsolved.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/do02reen24/Review/unsolved.md diff --git a/src/do02reen24/Review/unsolved.md b/src/do02reen24/Review/unsolved.md new file mode 100644 index 0000000..53b567a --- /dev/null +++ b/src/do02reen24/Review/unsolved.md @@ -0,0 +1,13 @@ +# 📚 unsolved problem + +## 📘 baekjoon + +- 이진 탐색 트리 (플래티넘5) [:link:](https://www.acmicpc.net/problem/2957) +- 스타트 택시 (골드4) [:link:](https://www.acmicpc.net/problem/19238) +- 러버덕을 사랑하는 모임 (실버1) [:link:](https://www.acmicpc.net/problem/18233) +- 달이 차오른다, 가자 (골드1) [:link:](https://www.acmicpc.net/problem/1194) +- 평범한 배낭 (골드5) [:link:](https://www.acmicpc.net/problem/12865) + +## 📗 programmers + +- 3차 자동완성 [:link:](https://programmers.co.kr/learn/courses/30/lessons/17685) From 97950b562fb8baaa5d7c16c1fcc378bba7f2e9ff Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Fri, 25 Dec 2020 14:34:23 +0900 Subject: [PATCH 126/193] solve : baekjoon 18233 --- src/do02reen24/Review/unsolved.md | 1 - src/do02reen24/Review/week7.md | 56 +++++++++++++++++--- src/do02reen24/brute-force/baekjoon_18233.py | 31 +++++++++++ 3 files changed, 80 insertions(+), 8 deletions(-) create mode 100644 src/do02reen24/brute-force/baekjoon_18233.py diff --git a/src/do02reen24/Review/unsolved.md b/src/do02reen24/Review/unsolved.md index 53b567a..2e2c741 100644 --- a/src/do02reen24/Review/unsolved.md +++ b/src/do02reen24/Review/unsolved.md @@ -4,7 +4,6 @@ - 이진 탐색 트리 (플래티넘5) [:link:](https://www.acmicpc.net/problem/2957) - 스타트 택시 (골드4) [:link:](https://www.acmicpc.net/problem/19238) -- 러버덕을 사랑하는 모임 (실버1) [:link:](https://www.acmicpc.net/problem/18233) - 달이 차오른다, 가자 (골드1) [:link:](https://www.acmicpc.net/problem/1194) - 평범한 배낭 (골드5) [:link:](https://www.acmicpc.net/problem/12865) diff --git a/src/do02reen24/Review/week7.md b/src/do02reen24/Review/week7.md index 881dedc..fb91e94 100644 --- a/src/do02reen24/Review/week7.md +++ b/src/do02reen24/Review/week7.md @@ -2,13 +2,13 @@ ## :ballot_box_with_check: 백준 1094 -* list를 사용하지 않고 풀고 싶었는데 잘안돼서 그냥 list로 풀었다. -* 스터디 고찰: 비트마스크를 써서 풀면 코드가 훨씬 간결함을 알게 되었다. +- list를 사용하지 않고 풀고 싶었는데 잘안돼서 그냥 list로 풀었다. +- 스터디 고찰: 비트마스크를 써서 풀면 코드가 훨씬 간결함을 알게 되었다. ## :ballot_box_with_check: 백준 14889 -* c++의 permutation을 쓰면 쉬울 것 같아 c++로 해결하였다. -* 스터디 고찰 : python의 경우 combination을 써서 풀 수 있음을 알게 되었다. +- c++의 permutation을 쓰면 쉬울 것 같아 c++로 해결하였다. +- 스터디 고찰 : python의 경우 combination을 써서 풀 수 있음을 알게 되었다. ## :ballot_box_with_check: 백준 18233 @@ -45,8 +45,8 @@ int main() { for (int i = 0; i < n; i++) { if (isGift[i] == 0) continue; int diff = member[i].second - member[i].first; - if (diff < remain) { - remain -= diff; + if (diff < remain) { + remain -= diff; sol[i] += diff; } else { @@ -63,5 +63,47 @@ int main() { } ``` -## :ballot_box_with_check: 백준 1194 +#### 틀렸습니다 (3%) + +```python +import sys +from itertools import combinations + +def rubberDuck(): + n, p, e = map(int, sys.stdin.readline().rstrip().split()) + member = [] + for _ in range(n): + minDuck, maxDuck = map(int, sys.stdin.readline().rstrip().split()) + member.append([minDuck, (maxDuck-minDuck)]) + user = [i for i in range(n)] + combList = list(combinations(user, p)) + + for comb in combList: + sol = [0] * n + remain = e + for i in comb: + sol[i] = member[i][0] + remain -= member[i][0] + if remain < 0: continue + for i in comb: + if remain > member[i][1]: + sol[i] += member[i][1] + remain -= member[i][1] + else: + sol[i] += remain + break + return ' '.join(map(str,sol)) + return -1 +print(rubberDuck()) +``` +- `return ' '.join(map(str,sol))`의 조건을 검사해주지 않아 틀렸음을 알게되었다. + +```python +if remain == 0: + return ' '.join(map(str,sol)) +``` + +위 처럼 인형을 모두 알맞게 나누어주었는지 검사해주어 해결할 수 있었다. + +## :ballot_box_with_check: 백준 1194 diff --git a/src/do02reen24/brute-force/baekjoon_18233.py b/src/do02reen24/brute-force/baekjoon_18233.py new file mode 100644 index 0000000..1be7433 --- /dev/null +++ b/src/do02reen24/brute-force/baekjoon_18233.py @@ -0,0 +1,31 @@ +import sys +from itertools import combinations + +def rubberDuck(): + n, p, e = map(int, sys.stdin.readline().rstrip().split()) + member = [] + for _ in range(n): + minDuck, maxDuck = map(int, sys.stdin.readline().rstrip().split()) + member.append([minDuck, (maxDuck-minDuck)]) + user = [i for i in range(n)] + combList = list(combinations(user, p)) + + for comb in combList: + sol = [0] * n + remain = e + for i in comb: + sol[i] = member[i][0] + remain -= member[i][0] + if remain < 0: continue + for i in comb: + if remain > member[i][1]: + sol[i] += member[i][1] + remain -= member[i][1] + else: + sol[i] += remain + remain = 0 + break + if remain == 0: + return ' '.join(map(str,sol)) + return -1 +print(rubberDuck()) From 0059cb2796137984fb6b90f504e79e106f40e026 Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Sun, 27 Dec 2020 11:12:57 +0900 Subject: [PATCH 127/193] =?UTF-8?q?docs:=2013=EC=A3=BC=EC=B0=A8=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=97=85=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index a9bc09b..3ef69aa 100644 --- a/README.md +++ b/README.md @@ -25,20 +25,21 @@ ## :green_book: Week Study -| | 1 | 2 | 3 | 4 | -| ------ | :------------------------------------------------------------------: | :-------------------------------------------------------------------------: | :-----------------------------------------------------: | :-----------------------------------------------------------: | -| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | -| 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | -| 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | -| 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | -| 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | -| 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | -| 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | -| 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | -| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | -| 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평범한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | -| 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | -| 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | +| | 1 | 2 | 3 | 4 | +| ------ | :----------------------------------------------------------: | :----------------------------------------------------------: | :-----------------------------------------------------: | :----------------------------------------------------------: | +| 1주차 | [요세푸스 문제](https://www.acmicpc.net/problem/1158) | [에디터](https://www.acmicpc.net/problem/1406) | [풍선 터뜨리기](https://www.acmicpc.net/problem/2346) | [이진 탐색 트리](https://www.acmicpc.net/problem/2957) | +| 2주차 | [절댓값 힙](https://www.acmicpc.net/problem/11286) | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [트리 순회](https://www.acmicpc.net/problem/1991) | [이진 탐색 트리 - 연장](https://www.acmicpc.net/problem/2957) | +| 3주차 | [자동완성](https://programmers.co.kr/learn/courses/30/lessons/17685) | [문자열 압축](https://programmers.co.kr/learn/courses/30/lessons/60057) | [그룹 단어 체커](https://www.acmicpc.net/problem/1316) | | +| 4주차 | [스타트 택시](https://www.acmicpc.net/problem/19238) | [자동완성 - 연장](https://programmers.co.kr/learn/courses/30/lessons/17685) | | | +| 5주차 | [숨바꼭질](https://www.acmicpc.net/problem/1697) | [바이러스](https://www.acmicpc.net/problem/2606) | [토마토](https://www.acmicpc.net/problem/7569) | | +| 6주차 | [쿼드트리](https://www.acmicpc.net/problem/1992) | [색종이 만들기](https://www.acmicpc.net/problem/2630) | [종이의 개수](https://www.acmicpc.net/problem/1780) | | +| 7주차 | [달이 차오른다, 가자.](https://www.acmicpc.net/problem/1194) | [러버덕을 사랑하는 모임](https://www.acmicpc.net/problem/18233) | [막대기](https://www.acmicpc.net/problem/1094) | [스타트와 링크](https://www.acmicpc.net/problem/14889) | +| 8주차 | [통나무 건너뛰기](https://www.acmicpc.net/problem/11497) | [신입 사원](https://www.acmicpc.net/problem/1946) | [동전 0](https://www.acmicpc.net/problem/11047) | | +| 9주차 | [1, 2, 3 더하기](https://www.acmicpc.net/problem/9095) | [평범한 배낭](https://www.acmicpc.net/problem/12865) | [2×n 타일링 2](https://www.acmicpc.net/problem/11727) | | +| 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평범한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | +| 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | +| 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | +| 13주차 | [미로탐색](https://www.acmicpc.net/problem/2178) | [암호코드](https://www.acmicpc.net/problem/2011) | [퀄린드롬(easy)](https://www.acmicpc.net/problem/20422) | [촌수계산](https://www.acmicpc.net/problem/2644) | ## :blue_book: Additional Study From f3475456faba65991b564977ca0d53a916f5e9e7 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sun, 27 Dec 2020 11:45:36 +0900 Subject: [PATCH 128/193] =?UTF-8?q?13=EC=A3=BC=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/boj/11399.md | 5 ++ src/grap3fruit/boj/11399.py | 17 ++++ src/grap3fruit/boj/17609.md | 154 ++++++++++++++++++++++++++++++++++++ src/grap3fruit/boj/17609.py | 36 +++++++++ 4 files changed, 212 insertions(+) create mode 100644 src/grap3fruit/boj/11399.md create mode 100644 src/grap3fruit/boj/11399.py create mode 100644 src/grap3fruit/boj/17609.md create mode 100644 src/grap3fruit/boj/17609.py diff --git a/src/grap3fruit/boj/11399.md b/src/grap3fruit/boj/11399.md new file mode 100644 index 0000000..541061b --- /dev/null +++ b/src/grap3fruit/boj/11399.md @@ -0,0 +1,5 @@ +# 11399 - 성공 + +## 구현 + +sort 이후 앞에서부터 더한 누산기의 합을 구해주면 된다. diff --git a/src/grap3fruit/boj/11399.py b/src/grap3fruit/boj/11399.py new file mode 100644 index 0000000..c9b4792 --- /dev/null +++ b/src/grap3fruit/boj/11399.py @@ -0,0 +1,17 @@ +import sys + +# n = int(sys.stdin.readline()) +# arr = list(map(int,sys.stdin.readline().strip().split())) + +arr = [3,1,4,3,2] + +arr.sort() +print(arr) + +acc = 0 +new_arr = [] +for el in arr: + acc += el + new_arr.append(acc) + +print(sum(new_arr)) \ No newline at end of file diff --git a/src/grap3fruit/boj/17609.md b/src/grap3fruit/boj/17609.md new file mode 100644 index 0000000..7bc0647 --- /dev/null +++ b/src/grap3fruit/boj/17609.md @@ -0,0 +1,154 @@ +# 17609 - 성공(힌트) + +## 펠린드롬 + +시도 1) + +```python +import sys + +def checkPD(data): + N = len(data) + + if N % 2 == 0: + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + return False + return True + + if N % 2 == 1: + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + return False + return True + +def get_new_string(data, idx): + arr_data = list(data) + del arr_data[idx] + return "".join(arr_data) + +def calc(data): + if checkPD(data) == True : + return 0 + + for i in range(len(data)): + result = get_new_string(data, i) + if checkPD(result): + return 1 + + return 2 + +N = int(sys.stdin.readline()) + +for _ in range(N) : + data = sys.stdin.readline().strip() + print(calc(data)) +``` + +시간초과 뜸. + +calc에서 포문이 n\*n으로 돌아서 그런것같다. + +시도 2) + +```python +import sys + +def checkPD1(data): + N = len(data) + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + return False + return True + +def checkPD2(data, idx): + N = len(data) + + left = 0 + right = 0 + # print(data, idx) + for i in range(0, int(N/2)): + if i == idx or N-i-1 == idx: + if idx < int(N/2): + left = 1 + if idx > int(N/2): + right = 1 + # print(i+left, " # ", N-i-1-right) + if data[i+left] != data[N-i-1-right] : + return 2 + + return 1 + +def calc(data): + if checkPD1(data) == True : + return 0 + + for i in range(len(data)): + result = checkPD2(data,i) + if result != 2: + return result + + return result + +# data = 'summuus' +# print(calc(data)) +N = int(sys.stdin.readline()) + +for _ in range(N) : + data = sys.stdin.readline().strip() + print(calc(data)) +``` + +checkPD2에 index를 넘겨주고 해당 index일때는 건너띄는 방식. + +이것도 calc에서 n만큼 돌고, 또 checkPD2에서 n만큼 돈다. 조금 적더라도 그래도 N^2에 가까움 + +시도 3) + +```python +import sys + +def checkPD2(data, start_idx, l_r_flag): + N = len(data) + left = 0 + right = 0 + + if l_r_flag == 'left': + left = 1 + if l_r_flag == 'right': + right = 1 + + for i in range(start_idx, int(N/2)): + if data[i+left] != data[N-i-1-right] : + return 2 + return 1 + +def checkPD1(data): + N = len(data) + + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + result = checkPD2(data, i, 'left') + if result == 1 : + return 1 + result = checkPD2(data, i, 'right') + return result + + return 0 + +N = int(sys.stdin.readline()) + +for _ in range(N) : + data = sys.stdin.readline().strip() + print(checkPD1(data)) +``` + +checkPD1을 돌다가, 서로 다른게 발견되면 "기회를 한번 더 준다" (사실 두번 더줌) + +checkPD2로 보내주는데 서로 다르기 때문에 왼쪽거를 한번 건너띄는 경우와, 오른쪽을 한번 건너띄는 경우 2번의 기회를 더 제공한다. + +그렇기때문에 N으로 도는 동안에 모두 해결될 수 있고, 많아도 left, right 2번이라 2N인듯 하다. + +혼자서 아이디어를 도출해내진 못했다 ㅠㅠ 구글링 해서 참고 했음. + +[https://awesomeroo.tistory.com/68](https://awesomeroo.tistory.com/68) diff --git a/src/grap3fruit/boj/17609.py b/src/grap3fruit/boj/17609.py new file mode 100644 index 0000000..b4ef557 --- /dev/null +++ b/src/grap3fruit/boj/17609.py @@ -0,0 +1,36 @@ +import sys + +def checkPD2(data, start_idx, l_r_flag): + N = len(data) + left = 0 + right = 0 + + if l_r_flag == 'left': + left = 1 + if l_r_flag == 'right': + right = 1 + + for i in range(start_idx, int(N/2)): + if data[i+left] != data[N-i-1-right] : + return 2 + return 1 + +def checkPD1(data): + N = len(data) + + for i in range(0, int(N/2)): + if data[i] != data[N-i-1] : + result = checkPD2(data, i, 'left') + if result == 1 : + return 1 + result = checkPD2(data, i, 'right') + return result + + return 0 + +N = int(sys.stdin.readline()) + +for _ in range(N) : + data = sys.stdin.readline().strip() + print(checkPD1(data)) + From cd3b4b6b53bde79f084c4b81035ca295f96f8f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 27 Dec 2020 19:53:49 +0900 Subject: [PATCH 129/193] boj 11399 --- src/kyu9341/boj11399_ATM/11399_ATM.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/kyu9341/boj11399_ATM/11399_ATM.cpp diff --git a/src/kyu9341/boj11399_ATM/11399_ATM.cpp b/src/kyu9341/boj11399_ATM/11399_ATM.cpp new file mode 100644 index 0000000..66e1383 --- /dev/null +++ b/src/kyu9341/boj11399_ATM/11399_ATM.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +using namespace std; + +int n; + +int main() { + cin >> n; + vector v(n); + int sum = 0; + + for (int i = 0; i < n; i++) cin >> v[i]; + + sort(v.begin(), v.end()); + + int now = 0; + for (int i = 0; i < n; i++) { + now = now + v[i]; + sum += now; + } + + cout << sum << '\n'; +} From 5df8382132ddb30d9d717efcb6d5f1d2b042006a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Sun, 27 Dec 2020 19:54:04 +0900 Subject: [PATCH 130/193] boj 17609 --- .../17609_\355\232\214\353\254\270.cpp" | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 "src/kyu9341/boj17609_\355\232\214\353\254\270/17609_\355\232\214\353\254\270.cpp" diff --git "a/src/kyu9341/boj17609_\355\232\214\353\254\270/17609_\355\232\214\353\254\270.cpp" "b/src/kyu9341/boj17609_\355\232\214\353\254\270/17609_\355\232\214\353\254\270.cpp" new file mode 100644 index 0000000..e1645da --- /dev/null +++ "b/src/kyu9341/boj17609_\355\232\214\353\254\270/17609_\355\232\214\353\254\270.cpp" @@ -0,0 +1,70 @@ +#include + +using namespace std; + +int t; + +int checkPalindrome(string str) { + int len = str.size(); + int left = 0; + int right = len - 1; + + int leftPoint; + int rightPoint; + + bool leftCheck = false; + bool rightCheck = false; + + while (left < right) { + if (str[left] != str[right]) { + if (rightCheck && leftCheck) return 2; + + if (!rightCheck && !leftCheck) { + leftPoint = left; + rightPoint = right; + if (left < right - 1) right--; + rightCheck = true; + continue; + } + + if (rightCheck) { + left = leftPoint; + right = rightPoint; + if (left + 1 < right) left++; + leftCheck = true; + continue; + } + + } + left++; + right--; + } + if (leftCheck || rightCheck) return 1; + return 0; +} + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + + string str; + + cin >> t; + cin.ignore(); + + while(t--) { + cin >> str; + cout << checkPalindrome(str) << '\n'; + } +} + +/* +풀이 +좌측 끝과 우측 끝에서 한칸씩 중앙으로 이동하며 회문인지 판별 +-> 좌측 포인터와 우측 포인터 값이 같지 않다면 먼저 우측 포인터를 한칸 더 이동시킨다. +-> 이후에 계속 진행하였을 때, 회문이라면 유사회문으로 판단 +-> 이후에 다시 값이 다른다면, 처음 값이 달랐던 지점으로 이동하여 왼쪽 포인터만 한칸 더 이동시킨다. +-> 이번에도 다시 값이 다르다면, 이 문자열은 회문도, 유사회문도 아님 +-> 계속 진행하였을 때, 회문이라면 유사회문으로 판단 +*/ From 6cac25b3032b89afac91d4d4d43e05c4e5174fcf Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 28 Dec 2020 15:03:28 +0900 Subject: [PATCH 131/193] unsolved : baekjoon 2011 --- src/do02reen24/Review/week13.md | 42 +++++++++++++++++++ .../dynamic-programming/baekjoon_2011.py | 20 +++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/do02reen24/Review/week13.md create mode 100644 src/do02reen24/dynamic-programming/baekjoon_2011.py diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md new file mode 100644 index 0000000..4266566 --- /dev/null +++ b/src/do02reen24/Review/week13.md @@ -0,0 +1,42 @@ +# :fire: week12 + +## :ballot_box_with_check: 백준 2011 + +#### 틀렸습니다 (35%) + +```python +import sys + +def decodeNum(): + word = sys.stdin.readline().rstrip() + length = len(word) + + sol = [1] * (length + 1) + for i in range(1, length): + prev = int(word[i-1]+word[i]) + now = int(word[i]) + if prev == 10 or prev == 20: + sol[i+1] = sol[i-1] + elif 11 <= prev and prev <= 26: + sol[i+1] = (sol[i] % 1000000) + (sol[i-1] % 1000000) + elif 1 <= now and now <= 9: + sol[i+1] = sol[i] + else: return 0 + return sol[length] % 1000000 + +print(int(decodeNum())) +``` + +- + +## :ballot_box_with_check: 백준 2178 + +- + +## :ballot_box_with_check: 백준 20422 + +- + +## :ballot_box_with_check: 백준 2644 + +- diff --git a/src/do02reen24/dynamic-programming/baekjoon_2011.py b/src/do02reen24/dynamic-programming/baekjoon_2011.py new file mode 100644 index 0000000..63cdfb8 --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_2011.py @@ -0,0 +1,20 @@ +import sys + +def decodeNum(): + word = sys.stdin.readline().rstrip() + length = len(word) + + sol = [1] * (length + 1) + for i in range(1, length): + prev = int(word[i-1]+word[i]) + now = int(word[i]) + if prev == 10 or prev == 20: + sol[i+1] = sol[i-1] + elif 11 <= prev and prev <= 26: + sol[i+1] = (sol[i] % 1000000) + (sol[i-1] % 1000000) + elif 1 <= now and now <= 9: + sol[i+1] = sol[i] + else: return 0 + return sol[length] % 1000000 + +print(int(decodeNum())) From b6e669fe4a864b4f0a7c311facee6af708b9e9c8 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 28 Dec 2020 16:27:41 +0900 Subject: [PATCH 132/193] solve : baekjoon 2178 --- src/do02reen24/BFS/baekjoon_2178.py | 28 +++++++++++++++++++++ src/do02reen24/Review/week13.md | 38 ++++++++++++++++++++++++++--- 2 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 src/do02reen24/BFS/baekjoon_2178.py diff --git a/src/do02reen24/BFS/baekjoon_2178.py b/src/do02reen24/BFS/baekjoon_2178.py new file mode 100644 index 0000000..31297e0 --- /dev/null +++ b/src/do02reen24/BFS/baekjoon_2178.py @@ -0,0 +1,28 @@ +import sys + +dx = [0, 0, -1, 1] +dy = [1, -1, 0, 0] + +n, m = map(int, sys.stdin.readline().split()) +board = [] +for _ in range(n): + board.append(sys.stdin.readline().rstrip()) + +visited = [[-1 for _ in range(m)] for _ in range(n)] +visited[0][0] = 1 +visit = [(0,0)] +new_visit = [] +while visit: + x, y = visit.pop() + for i in range(4): + mx = x + dx[i] + my = y + dy[i] + if mx >= 0 and mx < n and my >=0 and my < m: + if visited[mx][my] != -1 or board[mx][my] == "0": continue + visited[mx][my] = visited[x][y] + 1 + new_visit.append((mx, my)) + if not visit: + visit = new_visit + new_visit = [] + +print(visited[n-1][m-1]) \ No newline at end of file diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md index 4266566..69fa48d 100644 --- a/src/do02reen24/Review/week13.md +++ b/src/do02reen24/Review/week13.md @@ -27,11 +27,43 @@ def decodeNum(): print(int(decodeNum())) ``` -- - ## :ballot_box_with_check: 백준 2178 -- +- 초기에 `visited = [[-1] * m] * n` 와 같이 초기화를 했더니 2차원 배열이 같은 값들을 참조하여 동시에 값이 변경되는 문제가 있었다. `visited = [[-1 for _ in range(m)] for _ in range(n)]`와 같이 초기화하여 해결할 수 있었다. + +#### 런타임에러(72%) + +```python +import sys + +dx = [0, 0, -1, 1] +dy = [1, -1, 0, 0] + +def bfs(visit): + new_visit = [] + while visit: + x, y = visit.pop() + for i in range(4): + mx = x + dx[i] + my = y + dy[i] + if mx >= 0 and mx < n and my >=0 and my < m: + if visited[mx][my] != -1 or board[mx][my] == "0": continue + visited[mx][my] = visited[x][y] + 1 + new_visit.append((mx, my)) + if len(new_visit) > 0: bfs(new_visit) + +n, m = map(int, sys.stdin.readline().split()) +board = [] +for _ in range(n): + board.append(sys.stdin.readline().rstrip()) +visited = [[-1 for _ in range(m)] for _ in range(n)] +visited[0][0] = 1 +bfs([(0,0)]) +print(visited[n-1][m-1]) +``` + +- 파이썬은 재귀호출 깊이에 제한이 있는데 이를 풀어주지 않아 생긴 문제 같았다. +- 좀 더 생각해보니 재귀호출을 사용하지 않고 문제를 해결할 수 있을 것 같아 코드를 수정하여 문제를 해결하였다. ## :ballot_box_with_check: 백준 20422 From d11c6ba807dca3d19c0a6297edbd110eade18145 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 28 Dec 2020 16:43:34 +0900 Subject: [PATCH 133/193] solve : baekjoon 2011 --- src/do02reen24/Review/week13.md | 2 ++ src/do02reen24/dynamic-programming/baekjoon_2011.py | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md index 69fa48d..6674758 100644 --- a/src/do02reen24/Review/week13.md +++ b/src/do02reen24/Review/week13.md @@ -27,6 +27,8 @@ def decodeNum(): print(int(decodeNum())) ``` +- 숫자가 0인 경우를 예외처리해주고 1000000으로 나누는 부분을 수정함 + ## :ballot_box_with_check: 백준 2178 - 초기에 `visited = [[-1] * m] * n` 와 같이 초기화를 했더니 2차원 배열이 같은 값들을 참조하여 동시에 값이 변경되는 문제가 있었다. `visited = [[-1 for _ in range(m)] for _ in range(n)]`와 같이 초기화하여 해결할 수 있었다. diff --git a/src/do02reen24/dynamic-programming/baekjoon_2011.py b/src/do02reen24/dynamic-programming/baekjoon_2011.py index 63cdfb8..581a1ee 100644 --- a/src/do02reen24/dynamic-programming/baekjoon_2011.py +++ b/src/do02reen24/dynamic-programming/baekjoon_2011.py @@ -3,7 +3,7 @@ def decodeNum(): word = sys.stdin.readline().rstrip() length = len(word) - + if word[0] == '0': return 0 sol = [1] * (length + 1) for i in range(1, length): prev = int(word[i-1]+word[i]) @@ -11,10 +11,10 @@ def decodeNum(): if prev == 10 or prev == 20: sol[i+1] = sol[i-1] elif 11 <= prev and prev <= 26: - sol[i+1] = (sol[i] % 1000000) + (sol[i-1] % 1000000) + sol[i+1] = (sol[i] + sol[i-1]) % 1000000 elif 1 <= now and now <= 9: sol[i+1] = sol[i] else: return 0 - return sol[length] % 1000000 + return sol[length] print(int(decodeNum())) From ff4c8b3b1258c926d8daa2f8af2a20fd2e5f64d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Mon, 28 Dec 2020 18:01:25 +0900 Subject: [PATCH 134/193] =?UTF-8?q?=ED=8F=B4=EB=8D=94=20=EB=AA=85=20?= =?UTF-8?q?=EA=B3=B5=EB=B0=B1=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Main.java" | 0 .../Main.java" | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename "src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" => "src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254/Main.java" (100%) rename "src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" => "src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/Main.java" (100%) diff --git "a/src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" "b/src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254/Main.java" similarity index 100% rename from "src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254 /Main.java" rename to "src/kyu9341/boj1254_\355\214\260\353\246\260\353\223\234\353\241\254/Main.java" diff --git "a/src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" "b/src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/Main.java" similarity index 100% rename from "src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225 /Main.java" rename to "src/kyu9341/boj1932_\354\240\225\354\210\230\354\202\274\352\260\201\355\230\225/Main.java" From 809fb2fd75cebce6050be0f97556cf73a22f9cc2 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Mon, 28 Dec 2020 21:51:54 +0900 Subject: [PATCH 135/193] =?UTF-8?q?2644=EB=B2=88=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/boj/2644.md | 33 ++++++++++++++++++++++++ src/grap3fruit/boj/2644.py | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/grap3fruit/boj/2644.md create mode 100644 src/grap3fruit/boj/2644.py diff --git a/src/grap3fruit/boj/2644.md b/src/grap3fruit/boj/2644.md new file mode 100644 index 0000000..fbcd6b5 --- /dev/null +++ b/src/grap3fruit/boj/2644.md @@ -0,0 +1,33 @@ +# 2644 - 성공 + +## DFS + +그림과 같은 경우에 촌수 비교 방식을 6과 10을 비교한다면 + +1 → 2 → 4 → 8 → 10 + +1 → 2 → 6 + +에서, 공통되는 1 → 2 부분을 제외하고 길이를 더해주면 촌수가 됨. + +여기서 root가 항상 1이라거나, 부모가 항상 작은 수라거나 하는 조건이 없었기 때문에 + +트리의 root를 누구로 잡아줄까? 가 처음 이슈였다. + +모든 부모를 다 root로 해서 dfs로 체크해보면 어떨까? + +```python +for 부모 in 모든부모 : + dps(부모, target_A) + dps(부모, target_B) +``` + +모든 부모를 한번씩 다 root로 해주고 + +result가 제대로 나오는 경우에만 촌수를 계산해줌. + +result가 제대로 나오는 경우는, root로 부터 target_A와 target_B에 둘다 도달한 경우를 의미. + +dfs를 통해 target에 도달하게 되면 지나온 경로를 result_A, B 에 저장한다. + +result_A, B는 set 자료구조를 사용했으며, intersection을 사용하여 공통되는 부분을 제외해준다. diff --git a/src/grap3fruit/boj/2644.py b/src/grap3fruit/boj/2644.py new file mode 100644 index 0000000..b391fde --- /dev/null +++ b/src/grap3fruit/boj/2644.py @@ -0,0 +1,51 @@ +import sys + +N = int(sys.stdin.readline()) +A, B = map(int,sys.stdin.readline().strip().split()) +M = int(sys.stdin.readline()) + +dic = {} +for _ in range(M): + parent, child = map(int,sys.stdin.readline().strip().split()) + try: + if dic[parent] : + dic[parent].append(child) + except : + dic[parent] = [child] +print(dic) + +def dps(root, target, result): + try: + if dic[root]: + if target in dic[root]: + result.add(root) + result.add(target) + return True + + for el in dic[root]: + target_flag = dps(el, target, result) + if target_flag == True: + result.add(root) + return True + + except: + return False + + +def solution(N, A, B, M, dic): + for parent in dic : + result_A = set([parent]) + result_B = set([parent]) + dps(parent, A, result_A) + dps(parent, B, result_B) + + if (A in result_A) and (B in result_B): + intersec = result_A & result_B + # if len(result_A - intersec) == 1 and len(result_B - intersec) == 1: + # return 1 + + return abs(len(result_A - intersec) + len(result_B - intersec)) + + return -1 + +print(solution(N, A, B, M, dic)) \ No newline at end of file From 3c137ebec51006fea474adf6b41b0554794149fd Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 29 Dec 2020 17:16:33 +0900 Subject: [PATCH 136/193] solve : baekjoon 2644 --- src/do02reen24/BFS/baekjoon_2644.py | 26 ++++++++++++++++++++++++++ src/do02reen24/Review/week13.md | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 src/do02reen24/BFS/baekjoon_2644.py diff --git a/src/do02reen24/BFS/baekjoon_2644.py b/src/do02reen24/BFS/baekjoon_2644.py new file mode 100644 index 0000000..6fb6303 --- /dev/null +++ b/src/do02reen24/BFS/baekjoon_2644.py @@ -0,0 +1,26 @@ +import sys + +n = int(sys.stdin.readline()) +p1, p2 = map(lambda data: int(data)-1, sys.stdin.readline().split()) +relation = [[] for _ in range(n)] +m = int(sys.stdin.readline()) +for _ in range(m): + parent, children = map(lambda data: int(data)-1, sys.stdin.readline().split()) + relation[parent].append(children) + relation[children].append(parent) +cost = [-1 for _ in range(n)] +cost[p1] = 0 +count = 1 +queue = [p1] +new_queue = [] +while queue: + person = queue.pop() + for p in relation[person]: + if cost[p] != -1: continue + cost[p] = count + new_queue.append(p) + if not queue: + queue = new_queue + new_queue = [] + count = count + 1 +print(cost[p2]) \ No newline at end of file diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md index 6674758..9beb238 100644 --- a/src/do02reen24/Review/week13.md +++ b/src/do02reen24/Review/week13.md @@ -73,4 +73,4 @@ print(visited[n-1][m-1]) ## :ballot_box_with_check: 백준 2644 -- +- 상하좌우를 검사하는 bfs 문제와 다르게 서로의 관계를 따라가며 순차적으로 비용을 계산하도록 했다. From 7c4d30a2413df6f95c0449adb168f430cb5ce7cd Mon Sep 17 00:00:00 2001 From: Do Ho Kim <33643752+Do-ho@users.noreply.github.com> Date: Tue, 29 Dec 2020 17:39:48 +0900 Subject: [PATCH 137/193] =?UTF-8?q?docs:=2013=EC=A3=BC=EC=B0=A8=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ef69aa..9bf110f 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ | 10주차 | [다리 놓기](https://www.acmicpc.net/problem/1010) | [계단 오르기](https://www.acmicpc.net/problem/2579) | [RGB 거리](https://www.acmicpc.net/problem/1149) | [평범한 배낭 - 연장](https://www.acmicpc.net/problem/12865) | | 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | | 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | -| 13주차 | [미로탐색](https://www.acmicpc.net/problem/2178) | [암호코드](https://www.acmicpc.net/problem/2011) | [퀄린드롬(easy)](https://www.acmicpc.net/problem/20422) | [촌수계산](https://www.acmicpc.net/problem/2644) | +| 13주차 | [미로탐색](https://www.acmicpc.net/problem/2178) | [암호코드](https://www.acmicpc.net/problem/2011) | [떡먹는호랑이](https://www.acmicpc.net/problem/2502) | [촌수계산](https://www.acmicpc.net/problem/2644) | ## :blue_book: Additional Study From 0f89d1d14d53e4cf8f293eb0de60575fa107bf5a Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 29 Dec 2020 19:29:34 +0900 Subject: [PATCH 138/193] solve : baekjoon 2502 --- src/do02reen24/Review/week13.md | 8 +++---- .../dynamic-programming/baekjoon_2502.py | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 src/do02reen24/dynamic-programming/baekjoon_2502.py diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md index 9beb238..8624359 100644 --- a/src/do02reen24/Review/week13.md +++ b/src/do02reen24/Review/week13.md @@ -67,10 +67,10 @@ print(visited[n-1][m-1]) - 파이썬은 재귀호출 깊이에 제한이 있는데 이를 풀어주지 않아 생긴 문제 같았다. - 좀 더 생각해보니 재귀호출을 사용하지 않고 문제를 해결할 수 있을 것 같아 코드를 수정하여 문제를 해결하였다. -## :ballot_box_with_check: 백준 20422 - -- - ## :ballot_box_with_check: 백준 2644 - 상하좌우를 검사하는 bfs 문제와 다르게 서로의 관계를 따라가며 순차적으로 비용을 계산하도록 했다. + +## :ballot_box_with_check: 백준 2502 + +- fibonacci 를 활용하여 해결하였다. 재귀로 작성하게 될 경우 시간이 오래걸릴 것 같아 이전의 값을 재활용하도록 하였다. diff --git a/src/do02reen24/dynamic-programming/baekjoon_2502.py b/src/do02reen24/dynamic-programming/baekjoon_2502.py new file mode 100644 index 0000000..98ae5b1 --- /dev/null +++ b/src/do02reen24/dynamic-programming/baekjoon_2502.py @@ -0,0 +1,21 @@ +import sys + +def fibonacci(x): + if x < 2: return 1 + if data[x] != 0: return data[x] + else: + data[x] = fibonacci(x-1) + fibonacci(x-2) + return data[x] + +d, k = map(int, sys.stdin.readline().split()) +data = [0] * d + +f1 = fibonacci(d-3) +f2 = fibonacci(d-2) +for a in range(1, int(k/2) + 1): + sub = k - (f1 * a) + b = int(sub/f2) + if (f1 * a) + (f2 * b) == k: + print(a) + print(b) + break \ No newline at end of file From 1374db8b13cf6b83fb3a03a5110f488404a95ec4 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Tue, 29 Dec 2020 21:29:25 +0900 Subject: [PATCH 139/193] =?UTF-8?q?13=ED=9A=8C=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/boj/2178.md | 46 ++++++++++++++++++++++++++++ src/grap3fruit/boj/2178.py | 61 ++++++++++++++++++++++++++++++++++++++ src/grap3fruit/boj/2502.md | 16 ++++++++++ src/grap3fruit/boj/2502.py | 31 +++++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 src/grap3fruit/boj/2178.md create mode 100644 src/grap3fruit/boj/2178.py create mode 100644 src/grap3fruit/boj/2502.md create mode 100644 src/grap3fruit/boj/2502.py diff --git a/src/grap3fruit/boj/2178.md b/src/grap3fruit/boj/2178.md new file mode 100644 index 0000000..1538776 --- /dev/null +++ b/src/grap3fruit/boj/2178.md @@ -0,0 +1,46 @@ +# 2178 - 성공(힌트) + +## BFS + +bfs로 풀어서 성공 + +bfs에서 최단경로를 구할때는 q_size를 이용해서 큐에 넣기 전 계층 단위로 count 해주는 방법이 있다. + +또 다른 방법도 많은것 같은데. 일단 이것 이해하고 품.. + +테케 + +``` +2 2 +11 +11 + +3 3 +111 +111 +111 + +4 7 +1110111 +1011101 +1000001 +1111111 + +2 100 +1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 +1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 + +6 5 +11111 +10001 +10101 +10111 +10000 +11111 + +4 7 +1110110 +0011110 +0001011 +0001111 +``` diff --git a/src/grap3fruit/boj/2178.py b/src/grap3fruit/boj/2178.py new file mode 100644 index 0000000..27cbdb4 --- /dev/null +++ b/src/grap3fruit/boj/2178.py @@ -0,0 +1,61 @@ +import sys +from collections import deque + +N, M = map(int, sys.stdin.readline().strip().split()) +data = [[0]*(M+2)] +for _ in range(N): + input_arr = '0' + str(sys.stdin.readline().strip().split()[0]) + '0' + splited_arr = [int(i) for i in input_arr] + data.append(splited_arr) + +data.append([0]*(M+2)) +print(N, M, data) + + +def bfs(init, N, M, data): + global count + global visited + global queue + + queue.append(init) + while queue: + q_size = len(queue) + + for _ in range(q_size): + el = queue.popleft() + Y = el[0] + X = el[1] + if el not in visited and data[Y][X] == 1: + visited.append(el) + print(el) + + if X == M and Y == N: + print("도착") + print(visited) + print(count) + break + + right = [Y, X+1] + down = [Y+1, X] + left = [Y, X-1] + up = [Y-1, X] + + for pos in [right, down, left, up]: + if data[pos[0]][pos[1]] != 0: + queue.append(pos) + count += 1 + + +count = 1 +visited = [] +queue = deque([]) + + +def calc(N, M, data): + global count + global visited + init = [1, 1] + bfs(init, N, M, data) + + +calc(N, M, data) diff --git a/src/grap3fruit/boj/2502.md b/src/grap3fruit/boj/2502.md new file mode 100644 index 0000000..a0ee18a --- /dev/null +++ b/src/grap3fruit/boj/2502.md @@ -0,0 +1,16 @@ +# 2502 - 성공 + +## DP + +dp[n] = dp[n-1] + dp[n] +dp[1] = 'a' +dp[2] = 'b' + +로 주고, dp를 구하면 + +dp[K] = 'bababbab' 이런식으로 나온다. +이걸 + +count_a _ j + count_b _ i == K 식으로 바꿔서 + +i, j 이중포문 돌려서 구함 diff --git a/src/grap3fruit/boj/2502.py b/src/grap3fruit/boj/2502.py new file mode 100644 index 0000000..52006ca --- /dev/null +++ b/src/grap3fruit/boj/2502.py @@ -0,0 +1,31 @@ +import sys +D, K = list(map(int, input().split())) +dp = [0]*(D+1) + +dp[1] = 'a' +dp[2] = 'b' + +idx = 3 + +while True: + dp[idx] = dp[idx-2] + dp[idx-1] + + if idx == D: + print(dp) + break + + idx += 1 + +count_A = dp[D].count('a') +count_B = dp[D].count('b') + +def calc(count_A, count_B): + for i in range(1, K): + for j in range(1, K): + if (count_A * j + count_B * i) == K: + print(j) + print(i) + return + + +calc(count_A, count_B) From 82bfa178dc0892cb1acd7e562184f2341ac7e546 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 02:25:36 +0900 Subject: [PATCH 140/193] solve: boj 2178 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bfs를 통한 풀이 --- .../README.md" | 32 +++++++++++++++++++ .../boj_2178.py" | 25 +++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/README.md" create mode 100644 "src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/boj_2178.py" diff --git "a/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/README.md" "b/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/README.md" new file mode 100644 index 0000000..6ae8b04 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/README.md" @@ -0,0 +1,32 @@ +# 미로 탐색 + +- 31782KB, 132ms +- 너비 우선 탐색으로 해결 + +``` +import sys +from collections import deque + +D = [(1, 0), (0, 1), (-1, 0), (0, -1)] + +N, M = map(int, sys.stdin.readline().strip().split()) +MAZE = deque() +for _ in range(N): MAZE.append(sys.stdin.readline().strip()) + +q = deque() +visited = [[False for _ in range(M)] for _ in range(N)] +q.append((0,0,1)) +visited[0][0] = True + +while q: + tx, ty, moves = q.popleft() + if(tx == N-1 and ty == M-1): + sys.stdout.write(str(moves)+'\n') + break + for DIR in D: + nx, ny = [tx + DIR[0], ty + DIR[1]] + if(nx < 0 or nx >= N or ny < 0 or ny >= M): continue + if(MAZE[nx][ny] == '0' or visited[nx][ny]): continue + q.append((nx, ny, moves+1)) + visited[nx][ny] = True +``` diff --git "a/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/boj_2178.py" "b/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/boj_2178.py" new file mode 100644 index 0000000..20be861 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2178_\353\257\270\353\241\234\355\203\220\354\203\211/boj_2178.py" @@ -0,0 +1,25 @@ +import sys +from collections import deque + +D = [(1, 0), (0, 1), (-1, 0), (0, -1)] + +N, M = map(int, sys.stdin.readline().strip().split()) +MAZE = deque() +for _ in range(N): MAZE.append(sys.stdin.readline().strip()) + +q = deque() +visited = [[False for _ in range(M)] for _ in range(N)] +q.append((0,0,1)) +visited[0][0] = True + +while q: + tx, ty, moves = q.popleft() + if(tx == N-1 and ty == M-1): + sys.stdout.write(str(moves)+'\n') + break + for DIR in D: + nx, ny = [tx + DIR[0], ty + DIR[1]] + if(nx < 0 or nx >= N or ny < 0 or ny >= M): continue + if(MAZE[nx][ny] == '0' or visited[nx][ny]): continue + q.append((nx, ny, moves+1)) + visited[nx][ny] = True \ No newline at end of file From e338cb7afe138870a7c2a5c4c4dadd8d96d98643 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 02:25:51 +0900 Subject: [PATCH 141/193] solve: boj 2644 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dfs를 통한 풀이 --- .../README.md" | 5 +++ .../boj_2644.py" | 32 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/README.md" create mode 100644 "src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" diff --git "a/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/README.md" "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/README.md" new file mode 100644 index 0000000..da85a85 --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/README.md" @@ -0,0 +1,5 @@ +# 촌수 계산 + +dfs로 풀어버리자~~~ + +근데 ... exit()를 쓰면 런타임 오류가 나옴.. ㅠㅠ \ No newline at end of file diff --git "a/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" new file mode 100644 index 0000000..b911ddc --- /dev/null +++ "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" @@ -0,0 +1,32 @@ +import sys +from collections import deque + +n = int(sys.stdin.readline()) +a, b = map(int, sys.stdin.readline().rstrip().split()) +m = int(sys.stdin.readline()) + +r = {} + +for _ in range(m): + x, y = map(int, sys.stdin.readline().rstrip().split()) + try: r[x].append(y) + except: r[x] = [y] + try: r[y].append(x) + except: r[y] = [x] + +def bfs(): + q = deque() + q.append((a, 0)) + visited = [False for _ in range(n+1)] + + while(q): + target, chon = q.pop() + if(target == b): + return chon + for item in r[target]: + if(visited[item]): continue + q.append((item, chon+1)) + visited[item] = True + return -1 + +print(bfs()) \ No newline at end of file From 5aba3ae4c38c48b0ccdbd064c55b5ded159c5380 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 02:26:16 +0900 Subject: [PATCH 142/193] solve: boj 2502 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 피보나치 수열을 통한 풀이 --- .../README.md" | 62 +++++++++++++++++++ .../boj_2502.py" | 19 ++++++ 2 files changed, 81 insertions(+) create mode 100644 "src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/README.md" create mode 100644 "src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/boj_2502.py" diff --git "a/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/README.md" "b/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/README.md" new file mode 100644 index 0000000..1e27c9a --- /dev/null +++ "b/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/README.md" @@ -0,0 +1,62 @@ +# 떡 먹는 호랑이 + +R3 = R2 + R1 +R4 = R3 + R2 = R2 + R2 + R1 = 2R2 + R1 +R5 = R4 + R3 = 2R3 + R2 = 2(R2 + R1) + R2 = 3R2 + 2R1 +R6 = R5 + R4 = 2R4 + R3 = 2(2R2 + R1) + (R2 + R1) = 5R2 + 3R1 + +계수가 규칙이 있는듯! + +1 1 2 3 5 8 13 + +피보나치로 증가 + +R3 = 1 1 >> 얘가 1 1으로 시작하니 반복 시작하면 될듯 + +``` +import sys + +def calculate(a, b, A, B): + return a*A + b*B + +D, K = map(int, sys.stdin.readline().rstrip().split()) + +FIBO = [1 for _ in range(D)] +for i in range(2, D): + FIBO[i] = FIBO[i-1] + FIBO[i-2] + +a, b = FIBO[D-3], FIBO[D-2] + +def getResult(): + for i in range(1, K): + for j in range(1, K): + result = calculate(a, b, i, j) + if(result > K): break + if(result==K): + return str(i)+'\n'+str(j)+'\n' + +sys.stdout.write(getResult()) +``` + +반복문 하나 줄이기 +``` +import sys + +def calculate(a, b, A, B): + return a*A + b*B + +D, K = map(int, sys.stdin.readline().rstrip().split()) + +FIBO = [1 for _ in range(D)] +for i in range(2, D): + FIBO[i] = FIBO[i-1] + FIBO[i-2] + +a, b = FIBO[D-3], FIBO[D-2] + +def getResult(): + for i in range(1, K): + j = (K - a*i)/b + if j.is_integer(): return str(i)+'\n'+str(int(j))+'\n' + +sys.stdout.write(getResult()) +``` \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/boj_2502.py" "b/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/boj_2502.py" new file mode 100644 index 0000000..f32c5d7 --- /dev/null +++ "b/src/Do-ho/dp/boj_2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/boj_2502.py" @@ -0,0 +1,19 @@ +import sys + +def calculate(a, b, A, B): + return a*A + b*B + +D, K = map(int, sys.stdin.readline().rstrip().split()) + +FIBO = [1 for _ in range(D)] +for i in range(2, D): + FIBO[i] = FIBO[i-1] + FIBO[i-2] + +a, b = FIBO[D-3], FIBO[D-2] + +def getResult(): + for i in range(1, K): + j = (K - a*i)/b + if j.is_integer(): return str(i)+'\n'+str(int(j))+'\n' + +sys.stdout.write(getResult()) \ No newline at end of file From fad0e043806146b70946de9485901a3dff57b68a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Dec 2020 13:29:52 +0900 Subject: [PATCH 143/193] solve: boj 2178 --- ...0\353\241\234\355\203\220\354\203\211.cpp" | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 "src/kyu9341/boj2178_\353\257\270\353\241\234\355\203\220\354\203\211/2178_\353\257\270\353\241\234\355\203\220\354\203\211.cpp" diff --git "a/src/kyu9341/boj2178_\353\257\270\353\241\234\355\203\220\354\203\211/2178_\353\257\270\353\241\234\355\203\220\354\203\211.cpp" "b/src/kyu9341/boj2178_\353\257\270\353\241\234\355\203\220\354\203\211/2178_\353\257\270\353\241\234\355\203\220\354\203\211.cpp" new file mode 100644 index 0000000..35732a0 --- /dev/null +++ "b/src/kyu9341/boj2178_\353\257\270\353\241\234\355\203\220\354\203\211/2178_\353\257\270\353\241\234\355\203\220\354\203\211.cpp" @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include + +using namespace std; + +const int MAX = 100; +int n, m; +int dx[] = { 0, 0, 1, -1 }; +int dy[] = { 1, -1, 0, 0 }; +int map[MAX + 1][MAX + 1]; +int dist[MAX + 1][MAX + 1]; +queue< pair > q; + +void bfs(int sx, int sy) { + q.push(make_pair(sx, sy)); + dist[sx][sy] = 1; + + while(!q.empty()) { + int x = q.front().first; + int y = q.front().second; + q.pop(); + + for (int i = 0; i < 4; i++) { + int nx = x + dx[i]; + int ny = y + dy[i]; + + if (!(nx >= 0 && ny >= 0 && nx < n && ny < m)) continue; + if (dist[nx][ny] != -1 || map[nx][ny] != 1) continue; + q.push(make_pair(nx, ny)); + dist[nx][ny] = dist[x][y] + 1; + } + + if (dist[n - 1][m - 1] != -1) break; + } +} + +int main() { + + cin >> n >> m; + + memset(dist, -1, sizeof(dist)); + + for (int i = 0; i < n; i++) + for (int j = 0; j < m; j++) + scanf("%1d", &map[i][j]); + + bfs(0, 0); + + cout << dist[n - 1][m - 1] << '\n'; +} + +// C++ 사용자들 중에 숫자 하나씩을 떼어서 입력받고 싶어서 cin을 쓰다가 미로만 scanf로 입력받는 경우가 있습니다. 이 때에는 절대로 sync_with_stdio(false); 를 해서는 안 됩니다. From 2cdfaeb98ecd69010d86d415d4513b262287e2d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Dec 2020 13:30:15 +0900 Subject: [PATCH 144/193] solve: boj 2502 --- ...4\355\230\270\353\236\221\354\235\264.cpp" | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 "src/kyu9341/boj2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264.cpp" diff --git "a/src/kyu9341/boj2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264.cpp" "b/src/kyu9341/boj2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264.cpp" new file mode 100644 index 0000000..787b265 --- /dev/null +++ "b/src/kyu9341/boj2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264/2502_\353\226\241\353\250\271\353\212\224\355\230\270\353\236\221\354\235\264.cpp" @@ -0,0 +1,36 @@ +#include +#include + +using namespace std; + +int day, cake; + +int main() { + int A, B; + + cin >> day >> cake; + vector< pair > d(day + 1); + + d[1] = make_pair(1, 0); + d[2] = make_pair(0, 1); + + for (int i = 3; i <= day; i++) { + d[i].first = d[i - 1].first + d[i - 2].first; + d[i].second = d[i - 1].second + d[i - 2].second; + } + + for (int i = 1; i <= cake; i++) { + int cntA = d[day].first; + int cntB = d[day].second; + + if ((cake - cntA * i) % cntB == 0) { + A = i; + B = (cake - cntA * A) / cntB; + break; + } + } + + cout << A << '\n' << B << '\n'; +} + + From 96b8a28408eeeeee1ce532adefb86ca53ffc8b7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 30 Dec 2020 13:30:31 +0900 Subject: [PATCH 145/193] solve: boj 2644 --- ...4\354\210\230\352\263\204\354\202\260.cpp" | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 "src/kyu9341/boj2644_\354\264\214\354\210\230\352\263\204\354\202\260/2644_\354\264\214\354\210\230\352\263\204\354\202\260.cpp" diff --git "a/src/kyu9341/boj2644_\354\264\214\354\210\230\352\263\204\354\202\260/2644_\354\264\214\354\210\230\352\263\204\354\202\260.cpp" "b/src/kyu9341/boj2644_\354\264\214\354\210\230\352\263\204\354\202\260/2644_\354\264\214\354\210\230\352\263\204\354\202\260.cpp" new file mode 100644 index 0000000..6f91eec --- /dev/null +++ "b/src/kyu9341/boj2644_\354\264\214\354\210\230\352\263\204\354\202\260/2644_\354\264\214\354\210\230\352\263\204\354\202\260.cpp" @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +using namespace std; + +const int MAX = 100; +int n, m; +vector v[MAX + 1]; +int dist[MAX + 1]; + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + cout.tie(nullptr); + + int x, y; + + cin >> n >> x >> y >> m; + + memset(dist, -1, sizeof(dist)); + int parent, child; + + while (m--) { + cin >> parent >> child; + v[parent].push_back(child); + v[child].push_back(parent); + } + + queue q; + dist[x] = 0; + q.push(x); + + while(!q.empty()) { + int cur = q.front(); + q.pop(); + + for (int i = 0; i < v[cur].size(); i++) { + int next = v[cur][i]; + if (dist[next] != -1) continue; + dist[next] = dist[cur] + 1; + q.push(next); + } + + if (dist[y] != -1) break; + } + + cout << dist[y] << '\n'; +} + From a71058441e9e52d1fcb1dfc524f1fe4c3b9b01df Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Wed, 30 Dec 2020 14:09:31 +0900 Subject: [PATCH 146/193] =?UTF-8?q?13=ED=9A=8C=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=20=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/boj/2011.md | 18 ++++++++++++++++ src/grap3fruit/boj/2011.py | 43 ++++++++++++++++++++++++++++++++++++++ src/grap3fruit/boj/2502.md | 2 +- src/grap3fruit/boj/2644.py | 3 --- 4 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 src/grap3fruit/boj/2011.md create mode 100644 src/grap3fruit/boj/2011.py diff --git a/src/grap3fruit/boj/2011.md b/src/grap3fruit/boj/2011.md new file mode 100644 index 0000000..bf0d914 --- /dev/null +++ b/src/grap3fruit/boj/2011.md @@ -0,0 +1,18 @@ +# 2011 - 힌트 + +## DP + +처음엔 모든 경우의 수를 구해서, + +2개씩 묶이는게 0 0 and int(input[0]) < 3: + dp[1] = 1 + else: + return 0 + + if int(input[1]) != 0: # input[1]이 0이 아니고, + if (int(input[1]) < 7 and int(input[0]) == 2) or int(input[0]) == 1: # 10 ~ 26 사이면 + dp[1] = 2 + else: + dp[1] = 1 + + if len(input) == 2: # 입력이 두개면 return + return dp[1] + + n = 2 + while n < len(input): # dp[2] 부터 여기서 구함. + if int(input[n]) > 0: # input[n]이 0보다 클 경우는 input[n-1]에 그대로 붙여줄 수 있음. + dp[n] = dp[n-1] + + # n,n-1이 10 ~ 26 사이면, dp[n-2]에 10~26을 붙일 수 있음. + if (int(input[n]) < 7 and int(input[n-1]) == 2) or int(input[n-1]) == 1: + dp[n] = (dp[n-2] + dp[n]) + + n += 1 + + return(dp[len(input)-1] % 1000000) + + +print(calc(input, dp)) diff --git a/src/grap3fruit/boj/2502.md b/src/grap3fruit/boj/2502.md index a0ee18a..3d9e872 100644 --- a/src/grap3fruit/boj/2502.md +++ b/src/grap3fruit/boj/2502.md @@ -11,6 +11,6 @@ dp[2] = 'b' dp[K] = 'bababbab' 이런식으로 나온다. 이걸 -count_a _ j + count_b _ i == K 식으로 바꿔서 +count_a x j + count_b x i == K 식으로 바꿔서 i, j 이중포문 돌려서 구함 diff --git a/src/grap3fruit/boj/2644.py b/src/grap3fruit/boj/2644.py index b391fde..353c60d 100644 --- a/src/grap3fruit/boj/2644.py +++ b/src/grap3fruit/boj/2644.py @@ -41,9 +41,6 @@ def solution(N, A, B, M, dic): if (A in result_A) and (B in result_B): intersec = result_A & result_B - # if len(result_A - intersec) == 1 and len(result_B - intersec) == 1: - # return 1 - return abs(len(result_A - intersec) + len(result_B - intersec)) return -1 From a4db352ab7e765b220054e5b2e9e187e0fd8a34b Mon Sep 17 00:00:00 2001 From: SoonWon Kwon Date: Wed, 30 Dec 2020 14:12:48 +0900 Subject: [PATCH 147/193] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9bf110f..42a67d8 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ | 11주차 | [열차 시간표](https://www.acmicpc.net/problem/12731) | [정수 삼각형](https://www.acmicpc.net/problem/1932) | [팰린드롬 만들기](https://www.acmicpc.net/problem/1254) | | | 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | | 13주차 | [미로탐색](https://www.acmicpc.net/problem/2178) | [암호코드](https://www.acmicpc.net/problem/2011) | [떡먹는호랑이](https://www.acmicpc.net/problem/2502) | [촌수계산](https://www.acmicpc.net/problem/2644) | +| 14주차 | [크레인 인형뽑기](https://programmers.co.kr/learn/courses/30/lessons/64061) | [가장 긴 팰린드롬](https://programmers.co.kr/learn/courses/30/lessons/12904) | [튜플](https://programmers.co.kr/learn/courses/30/lessons/64065) | | ## :blue_book: Additional Study From 38060c3f739db328a2e3f7c8e6bf6de44e626c37 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 19:55:15 +0900 Subject: [PATCH 148/193] =?UTF-8?q?fix:=20boj=202644=20=EB=84=A4=EC=9D=B4?= =?UTF-8?q?=EB=B0=8D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../boj_2644.py" | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git "a/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" index b911ddc..62edba0 100644 --- "a/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" +++ "b/src/Do-ho/dfsbfs/boj_2644_\354\264\214\354\210\230\352\263\204\354\202\260/boj_2644.py" @@ -14,7 +14,7 @@ try: r[y].append(x) except: r[y] = [x] -def bfs(): +def dfs(): q = deque() q.append((a, 0)) visited = [False for _ in range(n+1)] @@ -29,4 +29,4 @@ def bfs(): visited[item] = True return -1 -print(bfs()) \ No newline at end of file +print(dfs()) \ No newline at end of file From fcb5fbbd00b9a059596af2b13f97bb4d41ffd5df Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 19:55:56 +0900 Subject: [PATCH 149/193] upload: boj 2011 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 아직 풀지 못했지만 업로드 --- .../README.md" | 40 ++++++++++++++++++ .../boj_2011.py" | 41 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 "src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/README.md" create mode 100644 "src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/boj_2011.py" diff --git "a/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/README.md" "b/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/README.md" new file mode 100644 index 0000000..166aa82 --- /dev/null +++ "b/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/README.md" @@ -0,0 +1,40 @@ +# 암호코드 + +탑다운으로 생각해서 적용해봄 재귀 너무 많이 도는 듯.. +```런다임 에러``` + +``` +import sys + +def isDivision(n): + return n>=10 and n<=26 + +def DP(n, l): + if (l<=0): return 0 + if (l==1): return 1 + if (l==2): + if(isDivision(int(n[:l]))): return 2 + return 1 + if(isDivision(int(n[l-2:l]))): return DP(n, l-1) + DP(n, l-2) + return DP(n, l-1) + +N = sys.stdin.readline().strip() +L = len(N) + +print(DP(N, L)%1000000) +``` + +바텀 업으로 풀어보자.... + +D(n) = D(n-1) + D(n-2) (분기가 될 경우) +D(n) = D(n-1) (분기가 되지 않을 경우) + +입력이 0인것도 처리... + +반례 찾기... +1. 100일때 -> 0 +2. 36036일때 -> 0 + +0앞에 1개나 2개가 잘못되면 안됨 + +100 \ No newline at end of file diff --git "a/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/boj_2011.py" "b/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/boj_2011.py" new file mode 100644 index 0000000..56dce24 --- /dev/null +++ "b/src/Do-ho/dp/boj_2011_\354\225\224\355\230\270\354\275\224\353\223\234/boj_2011.py" @@ -0,0 +1,41 @@ +import sys + +def isAlpha(n): + return int(n)>=1 and int(n)<=26 + +def isDivision(n): + return int(n)>10 and int(n)<=26 and int(n)!=20 + +def validation(n): + if(n[0]=='0'): return False + prev = n[0] + for i in range(1, len(n)): + if(n[i]=='0' and (prev != '1' and prev != '2')): return False + prev = n[i] + return True + +def decode(N): + L = len(N) + 1 + D = [0 for _ in range(L)] + if(not validation(N)): return 0 + D[0] = 1 + + if(isDivision(N[:2])): D[1] = 2 + else: D[1] = 1 + + if(L > 2): prev = N[1] + + for i in range(2, len(N)): + target = N[i] + word = prev + target + if(word=='10' or word=='20'): D[i] = D[i-2] + elif(not isAlpha(word)): D[i] = D[i-1] + elif(prev == '0'): D[i] = D[i-2] + elif(target == '0'): D[i] = D[i-2] + else: D[i] = D[i-1] + D[i-2] + prev = N[i] + print(D) + return D[L-2] % 1000000 + +N = sys.stdin.readline().strip() +print(decode(N)) \ No newline at end of file From 8899928212a9563823095cfeb932ec94a591526c Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 30 Dec 2020 20:30:34 +0900 Subject: [PATCH 150/193] =?UTF-8?q?solve:=20programmers=20=ED=81=AC?= =?UTF-8?q?=EB=A0=88=EC=9D=B8=EC=9D=B8=ED=98=95=EB=BD=91=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 단순 stack 구현 문제 - 직접 자료구조를 짜면서 해결 --- .../pgs_crane.js" | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 "src/Do-ho/implementation/pgs_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260/pgs_crane.js" diff --git "a/src/Do-ho/implementation/pgs_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260/pgs_crane.js" "b/src/Do-ho/implementation/pgs_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260/pgs_crane.js" new file mode 100644 index 0000000..c01bbaa --- /dev/null +++ "b/src/Do-ho/implementation/pgs_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260/pgs_crane.js" @@ -0,0 +1,45 @@ +class CraneStack { + constructor() { + this.store = []; + this.size = 0; + } + top() { + if(this.size==0) return 0; + return this.store[this.size-1]; + } + pushAndGetResult(item) { + if(this.top() === item) { + this.pop(); + this.size--; + return 2; + } + + this.store.push(item); + this.size++; + return 0; + } + pop() { return this.store.pop(); } +} + +const pickDoll = (board, x) => { + for(let i=0; i { + let answer = 0; + let basket = new CraneStack(); + + moves.forEach((item) => { + const doll = pickDoll(board, item-1); + if(doll!==0) answer += basket.pushAndGetResult(doll); + }) + + return answer; +} \ No newline at end of file From 3200a99dd0b32618c208241c99e762a106ee4df3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 03:03:58 +0900 Subject: [PATCH 151/193] =?UTF-8?q?docs=20:=20week14.md=20=ED=8C=8C?= =?UTF-8?q?=EC=9D=BC=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week13.md | 2 +- src/do02reen24/Review/week14.md | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 src/do02reen24/Review/week14.md diff --git a/src/do02reen24/Review/week13.md b/src/do02reen24/Review/week13.md index 8624359..d9f5559 100644 --- a/src/do02reen24/Review/week13.md +++ b/src/do02reen24/Review/week13.md @@ -1,4 +1,4 @@ -# :fire: week12 +# :fire: week13 ## :ballot_box_with_check: 백준 2011 diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md new file mode 100644 index 0000000..d4cefae --- /dev/null +++ b/src/do02reen24/Review/week14.md @@ -0,0 +1,9 @@ +# :fire: week14 + +- 이번주는 마이리얼트립 코딩테스트 준비를 위해 프로그래머스에서 `javascript`로 문제를 풀기로 하였다. + +## :ballot_box_with_check: 프로그래머스 튜플(64065) + +## :ballot_box_with_check: 프로그래머스 크레인 인형뽑기 게임(64061) + +## :ballot_box_with_check: 프로그래머스 가장 긴 팰린드롬(12904) From 3f654b86c30ffd816802e17288dfd72a3ab51900 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 15:17:46 +0900 Subject: [PATCH 152/193] =?UTF-8?q?solve=20:=20programmers=20=ED=8A=9C?= =?UTF-8?q?=ED=94=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week14.md | 3 ++ src/do02reen24/string/programmers_64065.js | 32 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/do02reen24/string/programmers_64065.js diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md index d4cefae..be4b0b3 100644 --- a/src/do02reen24/Review/week14.md +++ b/src/do02reen24/Review/week14.md @@ -4,6 +4,9 @@ ## :ballot_box_with_check: 프로그래머스 튜플(64065) +- python으로 문제를 풀다가 javascript로 문제를 푸니 헷갈렸다. +- 변수명과 함수 분리를 신경써서 코드를 작성하였다. + ## :ballot_box_with_check: 프로그래머스 크레인 인형뽑기 게임(64061) ## :ballot_box_with_check: 프로그래머스 가장 긴 팰린드롬(12904) diff --git a/src/do02reen24/string/programmers_64065.js b/src/do02reen24/string/programmers_64065.js new file mode 100644 index 0000000..df4a831 --- /dev/null +++ b/src/do02reen24/string/programmers_64065.js @@ -0,0 +1,32 @@ +const countingNumber = (arr) => { + const counts = {}; + arr.forEach((n) => (counts[n] = (counts[n] || 0) + 1)); + return counts; +}; + +const sortByValue = (dict) => { + const arr = []; + for (const key in dict) { + const value = dict[key]; + arr.push([Number(key), value]); + } + return arr.sort((pre, next) => next[1] - pre[1]); +}; + +const getKeyList = (arr) => { + const keys = []; + for (const pair of arr) { + const key = pair[0]; + keys.push(key); + } + return keys; +}; + +const solution = (s) => { + const deleteBracket = s.replace(/[{}]/gi, ''); + const numberList = deleteBracket.split(','); + const counts = countingNumber(numberList); + const valueList = sortByValue(counts); + const answer = getKeyList(valueList); + return answer; +}; From a32b07ac1bb0781b00cdae257af9c4854ca8050c Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 15:57:27 +0900 Subject: [PATCH 153/193] =?UTF-8?q?unsolved=20:=20programmers=20=EA=B0=80?= =?UTF-8?q?=EC=9E=A5=20=EA=B8=B4=20=ED=8C=B0=EB=A6=B0=EB=93=9C=EB=A1=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week14.md | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md index be4b0b3..195be89 100644 --- a/src/do02reen24/Review/week14.md +++ b/src/do02reen24/Review/week14.md @@ -10,3 +10,71 @@ ## :ballot_box_with_check: 프로그래머스 크레인 인형뽑기 게임(64061) ## :ballot_box_with_check: 프로그래머스 가장 긴 팰린드롬(12904) + +#### 정확성: 62.7, 효율성: 30.7 + +- 테스트 6번 12번 실패 + +```js +const isSameWord = (word, pre, next) => { + if (pre < 0 || next >= word.length) { + return false; + } + if (word[pre] !== word[next]) { + return false; + } + return true; +}; + +const oddPalindrome = (word, start) => { + let index = 1; + while (true) { + const pre = start - index; + const next = start + index; + if (isSameWord(word, pre, next)) { + index = index + 1; + continue; + } + index = index - 1; + break; + } + return index * 2 + 1; +}; + +const evenPalindrome = (word, start) => { + let index = 0; + while (true) { + const pre = start - index; + const next = start + 1 + index; + if (isSameWord(word, pre, next)) { + index = index + 1; + continue; + } + break; + } + return index * 2; +}; + +const isPalindrome = (word, start) => { + let length = oddPalindrome(word, start); + if (length === 1) { + const result = evenPalindrome(word, start); + if (result > length) { + length = result; + } + } + return length; +}; + +const solution = (s) => { + let maxLength = 0; + for (let index = 0; index < s.length; index++) { + const result = isPalindrome(s, index); + if (maxLength < result) { + maxLength = result; + } + } + + return maxLength; +}; +``` From f654f71732da23fb2df3e33add728d311886a5bb Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 16:16:22 +0900 Subject: [PATCH 154/193] =?UTF-8?q?solve=20:=20programmers=20=EA=B0=80?= =?UTF-8?q?=EC=9E=A5=20=EA=B8=B4=20=ED=8C=B0=EB=A6=B0=EB=93=9C=EB=A1=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week14.md | 2 + src/do02reen24/string/programmers_12904.js | 56 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/do02reen24/string/programmers_12904.js diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md index 195be89..687a366 100644 --- a/src/do02reen24/Review/week14.md +++ b/src/do02reen24/Review/week14.md @@ -78,3 +78,5 @@ const solution = (s) => { return maxLength; }; ``` + +- 처음 코드에서는 홀수 검사 결과가 있다면 짝수 검사를 진행하지 않았었는데, 짝수 검사의 결과가 더 큰 경우도 존재함을 알게 되었다. 따라서 두 경우를 모두 계산해주고 더 큰 값을 반환해주도록 변경하였다. diff --git a/src/do02reen24/string/programmers_12904.js b/src/do02reen24/string/programmers_12904.js new file mode 100644 index 0000000..7547c24 --- /dev/null +++ b/src/do02reen24/string/programmers_12904.js @@ -0,0 +1,56 @@ +const isSameWord = (word, pre, next) => { + if (pre < 0 || next >= word.length) { + return false; + } + if (word[pre] !== word[next]) { + return false; + } + return true; +}; + +const oddPalindrome = (word, start) => { + let index = 1; + while (true) { + const pre = start - index; + const next = start + index; + if (isSameWord(word, pre, next)) { + index = index + 1; + continue; + } + index = index - 1; + break; + } + return index * 2 + 1; +}; + +const evenPalindrome = (word, start) => { + let index = 0; + while (true) { + const pre = start - index; + const next = start + 1 + index; + if (isSameWord(word, pre, next)) { + index = index + 1; + continue; + } + break; + } + return index * 2; +}; + +const isPalindrome = (word, start) => { + const oddResult = oddPalindrome(word, start); + const evenResult = evenPalindrome(word, start); + return Math.max(oddResult, evenResult); +}; + +const solution = (s) => { + let maxLength = 0; + for (let index = 0; index < s.length; index++) { + const result = isPalindrome(s, index); + if (maxLength < result) { + maxLength = result; + } + } + + return maxLength; +}; From 2dc324199156a2508f6f49054516bdb688bfb6d6 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 16:38:48 +0900 Subject: [PATCH 155/193] =?UTF-8?q?unsolved=20:=20programmers=20=ED=81=AC?= =?UTF-8?q?=EB=A0=88=EC=9D=B8=20=EC=9D=B8=ED=98=95=EB=BD=91=EA=B8=B0=20?= =?UTF-8?q?=EA=B2=8C=EC=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week14.md | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md index 687a366..91fb1be 100644 --- a/src/do02reen24/Review/week14.md +++ b/src/do02reen24/Review/week14.md @@ -9,6 +9,41 @@ ## :ballot_box_with_check: 프로그래머스 크레인 인형뽑기 게임(64061) +#### 정확성 81.8 + +- 테스트 1번, 2번 실패 + +```js +const getTopDollIndex = (board, index) => { + let topIndex = -1; + for (const line of board) { + topIndex = topIndex + 1; + if (line[index] !== 0) break; + } + return topIndex; +}; + +const solution = (board, moves) => { + let answer = 0; + const basket = []; + for (const move of moves) { + const dollX = move - 1; + const dollY = getTopDollIndex(board, dollX); + const doll = board[dollY][dollX]; + board[dollY][dollX] = 0; + + const top = basket.pop(); + if (top === doll) { + answer = answer + 2; + } else { + basket.push(top); + basket.push(doll); + } + } + return answer; +}; +``` + ## :ballot_box_with_check: 프로그래머스 가장 긴 팰린드롬(12904) #### 정확성: 62.7, 효율성: 30.7 From 24ae46a1f2972bcd68725f4006a70ecaea9afca3 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Thu, 31 Dec 2020 16:50:16 +0900 Subject: [PATCH 156/193] =?UTF-8?q?solve=20:=20programmers=20=ED=81=AC?= =?UTF-8?q?=EB=A0=88=EC=9D=B8=20=EC=9D=B8=ED=98=95=20=EB=BD=91=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week14.md | 2 ++ .../simulation/programmers_64061.js | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/do02reen24/simulation/programmers_64061.js diff --git a/src/do02reen24/Review/week14.md b/src/do02reen24/Review/week14.md index 91fb1be..2c7d078 100644 --- a/src/do02reen24/Review/week14.md +++ b/src/do02reen24/Review/week14.md @@ -44,6 +44,8 @@ const solution = (board, moves) => { }; ``` +- 해당 열에 남은 인형이 없을 경우 예외처리를 해주었어야 했는데 기존의 코드는 0을 넣어주는 문제가 있음을 알게 되었다. 이에 대한 예외처리를 진행하여 해결할 수 있었다. + ## :ballot_box_with_check: 프로그래머스 가장 긴 팰린드롬(12904) #### 정확성: 62.7, 효율성: 30.7 diff --git a/src/do02reen24/simulation/programmers_64061.js b/src/do02reen24/simulation/programmers_64061.js new file mode 100644 index 0000000..cc390b6 --- /dev/null +++ b/src/do02reen24/simulation/programmers_64061.js @@ -0,0 +1,35 @@ +const getTopDollIndex = (board, index) => { + let topIndex = -1; + for (const line of board) { + topIndex = topIndex + 1; + if (line[index] !== 0) { + return topIndex; + } + } + return -1; +}; + +const solution = (board, moves) => { + let answer = 0; + const basket = []; + + for (const move of moves) { + const dollX = move - 1; + const dollY = getTopDollIndex(board, dollX); + if (dollY === -1) continue; + + const doll = board[dollY][dollX]; + board[dollY][dollX] = 0; + + const top = basket.pop(); + if (top === doll) { + answer = answer + 2; + continue; + } else if (top) { + basket.push(top); + } + basket.push(doll); + } + + return answer; +}; From 2fde9460f9ecec2db7266b64cedf03fbb893148d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Thu, 31 Dec 2020 17:36:36 +0900 Subject: [PATCH 157/193] =?UTF-8?q?solve:=20programmers=20=EA=B0=80?= =?UTF-8?q?=EC=9E=A5=20=EA=B8=B4=20=ED=8C=B0=EB=A6=B0=EB=93=9C=EB=A1=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 "src/kyu9341/programmers_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/index.js" diff --git "a/src/kyu9341/programmers_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/index.js" "b/src/kyu9341/programmers_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/index.js" new file mode 100644 index 0000000..684466e --- /dev/null +++ "b/src/kyu9341/programmers_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/index.js" @@ -0,0 +1,35 @@ +const getLongestPalindrome = (left, right, arrFromStr) => { + let maxLength = 0; + const isInRange = (left, right) => left >= 0 && right < arrFromStr.length; + + while (isInRange(left, right)) { + if (arrFromStr[left] !== arrFromStr[right]) return maxLength; + + maxLength = right - left + 1; + left -= 1; + right += 1; + } + + return maxLength; +}; + +const solution = s => { + let maxLength = 0; + const arrFromStr = [...s]; + + const checkLength = (_, index) => { + const odd = getLongestPalindrome(index, index, arrFromStr); + const even = getLongestPalindrome(index, index + 1, arrFromStr); + maxLength = Math.max(maxLength, Math.max(odd, even)); + }; + + arrFromStr.forEach(checkLength); + + return maxLength; +}; + +(() => { + const inputs = ['abcdcba', 'abacde']; + + inputs.forEach(input => console.log(solution(input))); +})(); From a5886a0aad9f21e3e20f0af1372f5c6445b8524e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Thu, 31 Dec 2020 17:37:13 +0900 Subject: [PATCH 158/193] =?UTF-8?q?solve:=20programmers=20=ED=81=AC?= =?UTF-8?q?=EB=A0=88=EC=9D=B8=20=EC=9D=B8=ED=98=95=20=EB=BD=91=EA=B8=B0=20?= =?UTF-8?q?=EA=B2=8C=EC=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 "src/kyu9341/programmers_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260\352\262\214\354\236\204/index.js" diff --git "a/src/kyu9341/programmers_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260\352\262\214\354\236\204/index.js" "b/src/kyu9341/programmers_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260\352\262\214\354\236\204/index.js" new file mode 100644 index 0000000..0734bcd --- /dev/null +++ "b/src/kyu9341/programmers_\355\201\254\353\240\210\354\235\270\354\235\270\355\230\225\353\275\221\352\270\260\352\262\214\354\236\204/index.js" @@ -0,0 +1,38 @@ +const range = (start, end) => + start < end ? Array.from({ length: end - start + 1 }, (_, idx) => idx + start) : []; + +const solution = (board, moves) => { + let count = 0; + const stack = []; + + const pickDoll = col => { + for (const row of range(0, board.length - 1)) { + const currentDoll = board[row][col - 1]; + board[row][col - 1] = 0; + + const isExist = currentDoll !== 0; + const isEqualToPrevDoll = stack[stack.length - 1] === currentDoll; + + if (isExist) { + if (isEqualToPrevDoll) { + stack.pop(); + count += 2; + break; + } + stack.push(currentDoll); + break; + } + } + }; + + moves.forEach(pickDoll); + return count; +} + +(() => { + const 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]]; + const moves = [1,5,3,5,1,2,1,4]; + + console.log(solution(board, moves)); +})(); + From 32e3d770a2873aa0aacfbb5ecad8ae713fe15b01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Thu, 31 Dec 2020 17:37:39 +0900 Subject: [PATCH 159/193] =?UTF-8?q?solve:=20programmers=20=ED=8A=9C?= =?UTF-8?q?=ED=94=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 "src/kyu9341/programmers_\355\212\234\355\224\214/index.js" diff --git "a/src/kyu9341/programmers_\355\212\234\355\224\214/index.js" "b/src/kyu9341/programmers_\355\212\234\355\224\214/index.js" new file mode 100644 index 0000000..ec57b1a --- /dev/null +++ "b/src/kyu9341/programmers_\355\212\234\355\224\214/index.js" @@ -0,0 +1,26 @@ +const parseStringToArray = str => str.substring(2, str.length - 2) + .split("},{") + .map(el => el.split(',').map(str => Number(str))); + +const solution = s => { + const set = new Set(); + const arr = parseStringToArray(s); + + const compareLength = (prev, cur) => prev.length - cur.length; + arr.sort(compareLength).flat().forEach(el => set.add(el));; + + return [...set]; +} + +(() => { + const inputs = [ + "{{2},{2,1},{2,1,3},{2,1,3,4}}", + "{{1,2,3},{2,1},{1,2,4,3},{2}}", + "{{20,111},{111}}", + "{{123}}", + "{{4,2,3},{3},{2,3,4,1},{2,3}}", + ]; + + inputs.forEach(input => console.log(solution(input))); +})(); + From 5cc8f5caf662e20aa1823870844b4fb9f197749e Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 31 Dec 2020 21:01:51 +0900 Subject: [PATCH 160/193] =?UTF-8?q?solve:=20programmers=20=ED=8A=9C?= =?UTF-8?q?=ED=94=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 고차함수를 많이 사용하려고 노력함 --- .../pgs_tuple.js" | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 "src/Do-ho/implementation/pgs_\355\212\234\355\224\214/pgs_tuple.js" diff --git "a/src/Do-ho/implementation/pgs_\355\212\234\355\224\214/pgs_tuple.js" "b/src/Do-ho/implementation/pgs_\355\212\234\355\224\214/pgs_tuple.js" new file mode 100644 index 0000000..b2f5b43 --- /dev/null +++ "b/src/Do-ho/implementation/pgs_\355\212\234\355\224\214/pgs_tuple.js" @@ -0,0 +1,25 @@ +const removeBracket = s => { + const re = /[0-9]+(,[0-9]+)*/g; + return s.match(re); +} + +const compareFunction = (prev, curr) => prev.length - curr.length; + +const parseStr = s => { + const strWithOutBracket = removeBracket(s); + const parsed = strWithOutBracket.reduce((acc, cur) => { + acc.push(cur.split(',')); + return acc; + }, []) + return parsed.sort(compareFunction); +} + +const solution = s => { + const parsedArr = parseStr(s); + const answer = parsedArr.reduce((acc, cur) => { + const filterItem = cur.filter((item) => !acc.includes(item)); + acc.push(filterItem[0]); + return acc; + }, []).map(item => parseInt(item)) + return answer; +} \ No newline at end of file From 0e3848dc872a393bf0c539be130f1532321f060d Mon Sep 17 00:00:00 2001 From: Do-ho Date: Thu, 31 Dec 2020 22:04:50 +0900 Subject: [PATCH 161/193] =?UTF-8?q?solve:=20programmers=20=EA=B0=80?= =?UTF-8?q?=EC=9E=A5=20=EA=B8=B4=20=ED=8C=B0=EB=A6=B0=EB=93=9C=EB=A1=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 한 index를 잡고 왼쪽과 오른쪽에 대한 검사를 함 - 짝수와 홀수의 경우에 다르게 처리되는 현상을 처리함 --- .../pgs_palindrome.js" | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 "src/Do-ho/implementation/pgs_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/pgs_palindrome.js" diff --git "a/src/Do-ho/implementation/pgs_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/pgs_palindrome.js" "b/src/Do-ho/implementation/pgs_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/pgs_palindrome.js" new file mode 100644 index 0000000..ce7affc --- /dev/null +++ "b/src/Do-ho/implementation/pgs_\352\260\200\354\236\245\352\270\264\355\214\260\353\246\260\353\223\234\353\241\254/pgs_palindrome.js" @@ -0,0 +1,21 @@ +const getOddPalindromeLength = (s, idx) => { return loopPalindrome(s, idx-1, idx+1, 1); } +const getEvenPalindromeLength = (s, idx) => { + if(s[idx] != s[idx+1]) return 0; + return loopPalindrome(s, idx-1, idx+2, 2); +} + +const loopPalindrome = (s, left, right, palindromeCount) => { + while(left >= 0 && right < s.length) { + if(s[left--] !== s[right++]) break; + palindromeCount += 2 + } + return palindromeCount; +} + +const solution = s => { + let answer = 0; + for (let i=0; i Date: Thu, 31 Dec 2020 22:20:17 +0900 Subject: [PATCH 162/193] =?UTF-8?q?14=ED=9A=8C=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/programmers/12904.js | 56 +++++++++++++++++++++ src/grap3fruit/programmers/12904.md | 72 +++++++++++++++++++++++++++ src/grap3fruit/programmers/64061.js | 37 ++++++++++++++ src/grap3fruit/programmers/64061.md | 25 ++++++++++ src/grap3fruit/programmers/64061_2.js | 40 +++++++++++++++ src/grap3fruit/programmers/64065.js | 46 +++++++++++++++++ src/grap3fruit/programmers/64065.md | 44 ++++++++++++++++ 7 files changed, 320 insertions(+) create mode 100644 src/grap3fruit/programmers/12904.js create mode 100644 src/grap3fruit/programmers/12904.md create mode 100644 src/grap3fruit/programmers/64061.js create mode 100644 src/grap3fruit/programmers/64061.md create mode 100644 src/grap3fruit/programmers/64061_2.js create mode 100644 src/grap3fruit/programmers/64065.js create mode 100644 src/grap3fruit/programmers/64065.md diff --git a/src/grap3fruit/programmers/12904.js b/src/grap3fruit/programmers/12904.js new file mode 100644 index 0000000..7d2fc3e --- /dev/null +++ b/src/grap3fruit/programmers/12904.js @@ -0,0 +1,56 @@ +const checkPD = (word, idx) => { + let max = 0; + const wordLength = word.length; + /* + 2가지가 될수 있다. + (1) baab + (2) aba + 둘다 돌고 max 구하자! + */ + + // 얘는 (2) aba + max = 1; + for (let i = 1; i < wordLength / 2; i++) { + if (word[idx - i] !== word[idx + i]) { + break; + } + max = i * 2 + 1; + } + + // 얘는 (1) baab + if (idx < word.length - 1 && word[idx] === word[idx + 1]) { + let maxCheck2 = 2; + if (maxCheck2 > max) { + max = maxCheck2; + } + + for (let i = 1; i < wordLength / 2; i++) { + if (word[idx - i] !== word[idx + i + 1]) { + break; + } + + maxCheck2 = i * 2 + 2; + if (maxCheck2 > max) { + max = maxCheck2; + } + } + } + return max; +}; + +const solution = (s) => { + let sArr = s.split(''); + let answer = 0; + + for (let i = 0; i < sArr.length; i++) { + let result = checkPD(sArr, i); + if (result > answer) { + answer = result; + } + } + + return answer; +}; + +// solution('ccabcbaa'); +console.log(solution('baaba')); diff --git a/src/grap3fruit/programmers/12904.md b/src/grap3fruit/programmers/12904.md new file mode 100644 index 0000000..3638877 --- /dev/null +++ b/src/grap3fruit/programmers/12904.md @@ -0,0 +1,72 @@ +# 12904 가장 긴 팰린드롬 - 성공 + +## 아이디어 구현 + +첫번째 풀이 + +``` +const checkPD = (word) => { + const wordLength = word.length; + + for (let i = 0; i < wordLength / 2; i++) { + if (word[i] !== word[wordLength - i - 1]) { + return false; + } + } + return true; +}; + +const solution = (s) => { + sArr = s.split(''); + answer = 0; + + sArr.reduce((accumulator, currentValue, currentIndex, array) => { + console.log(accumulator); + console.log(accumulator.join('')); + if (accumulator.length > 0 && checkPD(accumulator.join(''))) { + console.log(`${currentIndex}에서 펠린드롬입니다`); + answer = currentIndex; + } + + return [...accumulator, currentValue]; + }, []); + console.log(sArr); + + if (checkPD(sArr.join(''))) { + // console.log(`${sArr.length}에서 펠린드롬입니다`); + answer = sArr.length; + } + + console.log(answer); + return answer; +}; + +solution('abcabcdcbae'); +``` + +reduce써서 멋지게 풀어보려고 했지만, + +팰린드롬이 중간에 오는 경우 못찾는다. 항상 앞에서 붙여나가기 때문 ㅠ + +테케 `abcabcdcbae` 여기에 걸림 +`adcbbbbca` 이것도 안될듯. + +--- + +한개짜리일때 쫙 찾고, + +두개짜리일때 쫙 찾고 + +해야겠는걸. + +근데 이러면 효율성 통과 안될거같은데. + +위에 느낌으로 하려면, 큰거부터 찾자. 작은건 무조건 큰거까지 가야하지만 큰거는 되면 바로 끝내면 된다. + +--- + +위에꺼는 아닌것 같아 고민하다가 떠오름. + +하나씩 가면서 넓혀보기. 최대한 넓힌 max 리턴. << 이 방법. + +아이디어 싸움이었다. 못떠올렸으면 으으.. diff --git a/src/grap3fruit/programmers/64061.js b/src/grap3fruit/programmers/64061.js new file mode 100644 index 0000000..ab3b67f --- /dev/null +++ b/src/grap3fruit/programmers/64061.js @@ -0,0 +1,37 @@ +const 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], +]; +const moves = [1, 5, 3, 5, 1, 2, 1, 4]; + +const result = []; +let answer = 0; + +moves.forEach((move) => { + for (let i = 0; i < board.length; i++) { + if (board[i][move - 1] !== 0) { + if (result.length > 0) { + const prev = result.pop(); + + if (prev === board[i][move - 1]) { + board[i][move - 1] = 0; + answer += 2; + break; + } + + result.push(prev); + } + + result.push(board[i][move - 1]); + board[i][move - 1] = 0; + break; + } + } +}); + +console.log(board); +console.log(result); +console.log(answer); diff --git a/src/grap3fruit/programmers/64061.md b/src/grap3fruit/programmers/64061.md new file mode 100644 index 0000000..9229de2 --- /dev/null +++ b/src/grap3fruit/programmers/64061.md @@ -0,0 +1,25 @@ +# 64061 크레인 인형뽑기 게임 - 성공 + +## 구현 + +moves는 board의 x축에 접근하는데, + +이걸 이제 result stack에 넣고, + +stack에 넣을때 pop을 한번 해줘서 + +pop된 요소가 현재 넣는것과 동일하면 pass 하고 answer에 +2 해줌. + +동일 하지 않으면 pop 했던거 다시 넣고, 현재 요소 넣어줌. + +--- + +move.forEach는 reduce로 accumulator에 answer 넣어서 가능할것 같고. + +borad[i][move] 이거는 고차함수로 될까? + +외부에 flag 선언해놓고, 한번 0으로 바뀌면 flag 값 바꿔주면 될거같긴한데. 의미가 있나? for문이 더 빠를거같은데. + +속도 vs 가독성? + +> 구현해 보니 가독성이 좋은것 같지도 않다.. diff --git a/src/grap3fruit/programmers/64061_2.js b/src/grap3fruit/programmers/64061_2.js new file mode 100644 index 0000000..1ac2e7f --- /dev/null +++ b/src/grap3fruit/programmers/64061_2.js @@ -0,0 +1,40 @@ +const 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], +]; +const moves = [1, 5, 3, 5, 1, 2, 1, 4]; + +const result = []; +let answer = 0; + +moves.forEach((move) => { + let changedFlag = false; + + board.forEach((el) => { + if (el[move - 1] !== 0 && changedFlag === false) { + if (result.length > 0) { + const prev = result.pop(); + + if (prev === el[move - 1]) { + el[move - 1] = 0; + answer += 2; + changedFlag = true; + } else { + result.push(prev); + } + } + if (changedFlag === false) { + result.push(el[move - 1]); + el[move - 1] = 0; + changedFlag = true; + } + } + }); +}); + +console.log(board); +console.log(result); +console.log(answer); diff --git a/src/grap3fruit/programmers/64065.js b/src/grap3fruit/programmers/64065.js new file mode 100644 index 0000000..d6902cc --- /dev/null +++ b/src/grap3fruit/programmers/64065.js @@ -0,0 +1,46 @@ +const getDividedArr = (arrA, arrB) => { + return arrB.filter((el) => !arrA.includes(el)); +}; + +function solution(s) { + let answer = []; + + const arrS = s.split(''); + + let mother_arr = []; + let child_arr = []; + + for (let i = 1; i < arrS.length - 1; i++) { + if (arrS[i] === '}') { + mother_arr.push(child_arr); + child_arr = []; + } + + if (+arrS[i] >= 0) { + if (+arrS[i - 1] >= 0) { + const num = child_arr.pop(); + child_arr.push(Number(num + arrS[i])); + } else { + child_arr.push(+arrS[i]); + } + } + } + console.log(mother_arr); // 여기 까지 {} 문자열을 [] 배열로 바꿈. + + for (let i = 0; i < mother_arr.length; i++) { + for (let j = 0; j < mother_arr.length; j++) { + if (mother_arr[j].length === i + 1) { + const [temp] = getDividedArr(answer, mother_arr[j]); + answer.push(temp); + } + } + } + + return answer; +} + +console.log(solution('{{2},{2,1},{2,1,3},{2,1,3,4}}')); +console.log(solution('{{1,2,3},{2,1},{1,2,4,3},{2}}')); +console.log(solution('{{20,111},{111}}')); +console.log(solution('{{123}}')); +console.log(solution('{{4,2,3},{3},{2,3,4,1},{2,3}}')); diff --git a/src/grap3fruit/programmers/64065.md b/src/grap3fruit/programmers/64065.md new file mode 100644 index 0000000..f4cf3d6 --- /dev/null +++ b/src/grap3fruit/programmers/64065.md @@ -0,0 +1,44 @@ +# 64065 2019 카카오 겨울인턴 튜플 - 성공 + +## 구현 + +집합 길이에 따라서 + +가장 작은게 맨 앞이고 + +그 다음 길이에 추가된게 다음꺼 + +이런식으로 result 채우면 됨. + +python에 set 쓰면 엄청 쉬웠을듯 ㅋㅋ + +--- + +1. {} 문자열을 [] 배열로 바꾼다. + +``` +부모 arr, 자식 arr를 둔다. +이차원 배열의 바깥을 부모 arr. +내부 el들이 자식 arr. + +전체 string 길이만큼 loop를 돌면서 + 만약 '}' 면 + 부모에 현재까지 자식 arr 추가. + 자식 arr = [] + + '}' 가 아닐떄 + 앞이 숫자면 합쳐서 자식arr에 넣고 + 아니면 그냥 넣음. + + +``` + +2. 배열 갯수만큼 이중포문 돈다. + +``` +for i = 1,2,3 ... + for j = 1,2,3 ... + 만약 현재 배열의 길이가 i이면, + answer에 추가. + +``` From 17aa5bfc404b12481062b276af0af5ce315140f4 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Fri, 1 Jan 2021 13:15:06 +0900 Subject: [PATCH 163/193] [refactor] week14 code --- src/grap3fruit/programmers/12904.js | 37 +++++------------- src/grap3fruit/programmers/64061.js | 39 +++++++++++-------- src/grap3fruit/programmers/64065.js | 60 ++++++++++++++++++----------- 3 files changed, 69 insertions(+), 67 deletions(-) diff --git a/src/grap3fruit/programmers/12904.js b/src/grap3fruit/programmers/12904.js index 7d2fc3e..ef69dc0 100644 --- a/src/grap3fruit/programmers/12904.js +++ b/src/grap3fruit/programmers/12904.js @@ -1,38 +1,22 @@ -const checkPD = (word, idx) => { +const getMaxOddPalindrome = (word, idx) => { let max = 0; - const wordLength = word.length; - /* - 2가지가 될수 있다. - (1) baab - (2) aba - 둘다 돌고 max 구하자! - */ - - // 얘는 (2) aba - max = 1; - for (let i = 1; i < wordLength / 2; i++) { + for (let i = 0; i < word.length / 2; i++) { if (word[idx - i] !== word[idx + i]) { break; } max = i * 2 + 1; } + return max; +}; - // 얘는 (1) baab +const getMaxEvenPalindrome = (word, idx) => { + let max = 0; if (idx < word.length - 1 && word[idx] === word[idx + 1]) { - let maxCheck2 = 2; - if (maxCheck2 > max) { - max = maxCheck2; - } - - for (let i = 1; i < wordLength / 2; i++) { + for (let i = 0; i < word.length / 2; i++) { if (word[idx - i] !== word[idx + i + 1]) { break; } - - maxCheck2 = i * 2 + 2; - if (maxCheck2 > max) { - max = maxCheck2; - } + max = i * 2 + 2; } } return max; @@ -43,10 +27,7 @@ const solution = (s) => { let answer = 0; for (let i = 0; i < sArr.length; i++) { - let result = checkPD(sArr, i); - if (result > answer) { - answer = result; - } + answer = Math.max(answer, getMaxOddPalindrome(sArr, i), getMaxEvenPalindrome(sArr, i)); } return answer; diff --git a/src/grap3fruit/programmers/64061.js b/src/grap3fruit/programmers/64061.js index ab3b67f..246ddd8 100644 --- a/src/grap3fruit/programmers/64061.js +++ b/src/grap3fruit/programmers/64061.js @@ -7,31 +7,38 @@ const board = [ ]; const moves = [1, 5, 3, 5, 1, 2, 1, 4]; -const result = []; -let answer = 0; +function solution(board, moves) { + const result = []; + let answer = 0; -moves.forEach((move) => { - for (let i = 0; i < board.length; i++) { - if (board[i][move - 1] !== 0) { - if (result.length > 0) { - const prev = result.pop(); + moves.reduce((acc, move) => { + for (let i = 0; i < board.length; i++) { + if (board[i][move - 1] === 0) { + continue; + } + + if (acc.length > 0) { + const prev = acc.pop(); if (prev === board[i][move - 1]) { board[i][move - 1] = 0; answer += 2; - break; + return acc; } - result.push(prev); + acc.push(prev); } - result.push(board[i][move - 1]); + acc.push(board[i][move - 1]); board[i][move - 1] = 0; - break; + return acc; } - } -}); + return acc; + }, []); + + console.log(board); + console.log(result); + return answer; +} -console.log(board); -console.log(result); -console.log(answer); +console.log(solution(board, moves)); diff --git a/src/grap3fruit/programmers/64065.js b/src/grap3fruit/programmers/64065.js index d6902cc..0ecd3d3 100644 --- a/src/grap3fruit/programmers/64065.js +++ b/src/grap3fruit/programmers/64065.js @@ -1,37 +1,41 @@ -const getDividedArr = (arrA, arrB) => { +const getSubtractedArr = (arrA, arrB) => { return arrB.filter((el) => !arrA.includes(el)); }; -function solution(s) { - let answer = []; +const getArrFromStr = (s) => { + const arr = s.split(''); - const arrS = s.split(''); - - let mother_arr = []; + let parent_arr = []; let child_arr = []; - for (let i = 1; i < arrS.length - 1; i++) { - if (arrS[i] === '}') { - mother_arr.push(child_arr); + for (let i = 1; i < arr.length - 1; i++) { + if (arr[i] === '}') { + parent_arr.push(child_arr); child_arr = []; } - if (+arrS[i] >= 0) { - if (+arrS[i - 1] >= 0) { + if (+arr[i] >= 0) { + if (+arr[i - 1] >= 0) { const num = child_arr.pop(); - child_arr.push(Number(num + arrS[i])); + child_arr.push(Number(num + arr[i])); } else { - child_arr.push(+arrS[i]); + child_arr.push(+arr[i]); } } } - console.log(mother_arr); // 여기 까지 {} 문자열을 [] 배열로 바꿈. + return parent_arr; +}; + +function solution(s) { + let answer = []; + const arr = getArrFromStr(s); - for (let i = 0; i < mother_arr.length; i++) { - for (let j = 0; j < mother_arr.length; j++) { - if (mother_arr[j].length === i + 1) { - const [temp] = getDividedArr(answer, mother_arr[j]); + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr.length; j++) { + if (arr[j].length === i + 1) { + const [temp] = getSubtractedArr(answer, arr[j]); answer.push(temp); + break; } } } @@ -39,8 +43,18 @@ function solution(s) { return answer; } -console.log(solution('{{2},{2,1},{2,1,3},{2,1,3,4}}')); -console.log(solution('{{1,2,3},{2,1},{1,2,4,3},{2}}')); -console.log(solution('{{20,111},{111}}')); -console.log(solution('{{123}}')); -console.log(solution('{{4,2,3},{3},{2,3,4,1},{2,3}}')); +// console.log(solution('{{2},{2,1},{2,1,3},{2,1,3,4}}')); +// console.log(solution('{{1,2,3},{2,1},{1,2,4,3},{2}}')); +// console.log(solution('{{20,111},{111}}')); +// console.log(solution('{{123}}')); +// console.log(solution('{{4,2,3},{3},{2,3,4,1},{2,3}}')); + +const setA = new Set(); +const setB = new Set(); +setA.add(1); +setA.add(2); +setB.add(3); +setB.add(2); + +console.log(setA, setB); +console.log(setA - setB); From 1e15d26a82e095be6dba3e05dcfdc2d188a921da Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Fri, 1 Jan 2021 13:16:18 +0900 Subject: [PATCH 164/193] [refactor] week14 code --- src/grap3fruit/programmers/64065.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/grap3fruit/programmers/64065.js b/src/grap3fruit/programmers/64065.js index 0ecd3d3..e22cf06 100644 --- a/src/grap3fruit/programmers/64065.js +++ b/src/grap3fruit/programmers/64065.js @@ -1,6 +1,4 @@ -const getSubtractedArr = (arrA, arrB) => { - return arrB.filter((el) => !arrA.includes(el)); -}; +const getSubtractedArr = (arrA, arrB) => arrB.filter((el) => !arrA.includes(el)); const getArrFromStr = (s) => { const arr = s.split(''); From 8e6e635c772c820e12cc3c797d49882e290bd712 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sat, 2 Jan 2021 14:44:01 +0900 Subject: [PATCH 165/193] =?UTF-8?q?[refactor]=20programmers=20=EB=82=B4?= =?UTF-8?q?=EB=B6=80=20js/py=20=ED=8F=B4=EB=8D=94=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/programmers/{ => js}/12904.js | 0 src/grap3fruit/programmers/{ => js}/12904.md | 0 src/grap3fruit/programmers/{ => js}/64061.js | 0 src/grap3fruit/programmers/{ => js}/64061.md | 0 src/grap3fruit/programmers/{ => js}/64061_2.js | 0 src/grap3fruit/programmers/{ => js}/64065.js | 0 src/grap3fruit/programmers/{ => js}/64065.md | 0 src/grap3fruit/programmers/{ => py}/17685.py | 0 src/grap3fruit/programmers/{ => py}/42578.py | 0 src/grap3fruit/programmers/{ => py}/60057.py | 0 10 files changed, 0 insertions(+), 0 deletions(-) rename src/grap3fruit/programmers/{ => js}/12904.js (100%) rename src/grap3fruit/programmers/{ => js}/12904.md (100%) rename src/grap3fruit/programmers/{ => js}/64061.js (100%) rename src/grap3fruit/programmers/{ => js}/64061.md (100%) rename src/grap3fruit/programmers/{ => js}/64061_2.js (100%) rename src/grap3fruit/programmers/{ => js}/64065.js (100%) rename src/grap3fruit/programmers/{ => js}/64065.md (100%) rename src/grap3fruit/programmers/{ => py}/17685.py (100%) rename src/grap3fruit/programmers/{ => py}/42578.py (100%) rename src/grap3fruit/programmers/{ => py}/60057.py (100%) diff --git a/src/grap3fruit/programmers/12904.js b/src/grap3fruit/programmers/js/12904.js similarity index 100% rename from src/grap3fruit/programmers/12904.js rename to src/grap3fruit/programmers/js/12904.js diff --git a/src/grap3fruit/programmers/12904.md b/src/grap3fruit/programmers/js/12904.md similarity index 100% rename from src/grap3fruit/programmers/12904.md rename to src/grap3fruit/programmers/js/12904.md diff --git a/src/grap3fruit/programmers/64061.js b/src/grap3fruit/programmers/js/64061.js similarity index 100% rename from src/grap3fruit/programmers/64061.js rename to src/grap3fruit/programmers/js/64061.js diff --git a/src/grap3fruit/programmers/64061.md b/src/grap3fruit/programmers/js/64061.md similarity index 100% rename from src/grap3fruit/programmers/64061.md rename to src/grap3fruit/programmers/js/64061.md diff --git a/src/grap3fruit/programmers/64061_2.js b/src/grap3fruit/programmers/js/64061_2.js similarity index 100% rename from src/grap3fruit/programmers/64061_2.js rename to src/grap3fruit/programmers/js/64061_2.js diff --git a/src/grap3fruit/programmers/64065.js b/src/grap3fruit/programmers/js/64065.js similarity index 100% rename from src/grap3fruit/programmers/64065.js rename to src/grap3fruit/programmers/js/64065.js diff --git a/src/grap3fruit/programmers/64065.md b/src/grap3fruit/programmers/js/64065.md similarity index 100% rename from src/grap3fruit/programmers/64065.md rename to src/grap3fruit/programmers/js/64065.md diff --git a/src/grap3fruit/programmers/17685.py b/src/grap3fruit/programmers/py/17685.py similarity index 100% rename from src/grap3fruit/programmers/17685.py rename to src/grap3fruit/programmers/py/17685.py diff --git a/src/grap3fruit/programmers/42578.py b/src/grap3fruit/programmers/py/42578.py similarity index 100% rename from src/grap3fruit/programmers/42578.py rename to src/grap3fruit/programmers/py/42578.py diff --git a/src/grap3fruit/programmers/60057.py b/src/grap3fruit/programmers/py/60057.py similarity index 100% rename from src/grap3fruit/programmers/60057.py rename to src/grap3fruit/programmers/py/60057.py From ba208959c69bc44993392013ffa9069cf1cca641 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sat, 2 Jan 2021 14:44:46 +0900 Subject: [PATCH 166/193] =?UTF-8?q?=EA=B5=AC=EB=A6=84=20=EC=BD=94=ED=85=8C?= =?UTF-8?q?=20=EC=97=B0=EC=8A=B5=20&=20nodejs=20input=20=EC=BC=80=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/goorm/43089.js | 27 ++++++++++++++ src/grap3fruit/goorm/43125.js | 29 +++++++++++++++ src/grap3fruit/goorm/88520.js | 64 ++++++++++++++++++++++++++++++++ src/grap3fruit/goorm/input.js | 33 ++++++++++++++++ src/grap3fruit/goorm/input1_2.js | 37 ++++++++++++++++++ src/grap3fruit/goorm/input2.js | 33 ++++++++++++++++ 6 files changed, 223 insertions(+) create mode 100644 src/grap3fruit/goorm/43089.js create mode 100644 src/grap3fruit/goorm/43125.js create mode 100644 src/grap3fruit/goorm/88520.js create mode 100644 src/grap3fruit/goorm/input.js create mode 100644 src/grap3fruit/goorm/input1_2.js create mode 100644 src/grap3fruit/goorm/input2.js diff --git a/src/grap3fruit/goorm/43089.js b/src/grap3fruit/goorm/43089.js new file mode 100644 index 0000000..26169ca --- /dev/null +++ b/src/grap3fruit/goorm/43089.js @@ -0,0 +1,27 @@ +// Run by Node.js +const getResultLength = (data) => { + dataArr = data[0].split(''); + // console.log(dataArr) + const result = dataArr.filter((el) => el === data[1]); + return result.length; +}; + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let count = 0; +let n = 2; +data = []; +rl.on('line', function (line) { + data.push(line); + count += 1; + if (count === n) { + rl.close(); + } +}).on('close', function () { + console.log(getResultLength(data)); + process.exit(); +}); diff --git a/src/grap3fruit/goorm/43125.js b/src/grap3fruit/goorm/43125.js new file mode 100644 index 0000000..9087227 --- /dev/null +++ b/src/grap3fruit/goorm/43125.js @@ -0,0 +1,29 @@ +// Run by Node.js + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let N = 0; +// const data = []; +let count = 0; + +rl.on('line', function (line) { + if (!N) { + N = +line; + } else { + const data = line.split(' ').map((el) => +el); + let min = data[0]; + for (let i = 1; i < data.length; i++) { + if (data[i] < min) { + min = data[i]; + } + } + console.log(min); + rl.close(); + } +}).on('close', function () { + process.exit(); +}); diff --git a/src/grap3fruit/goorm/88520.js b/src/grap3fruit/goorm/88520.js new file mode 100644 index 0000000..cb71b2c --- /dev/null +++ b/src/grap3fruit/goorm/88520.js @@ -0,0 +1,64 @@ +const print = (data) => { + console.log(data); +}; + +const getTrashCount = (data, A, B, K) => { + let count = 0; + for (let i = A; i < A + K; i++) { + for (let j = B; j < B + K; j++) { + if (data[i][j] === 1) { + count += 1; + } + } + } + return count; +}; + +const solution = (data, info) => { + const [N, K] = info; + let min_result = K * K; + for (let i = 0; i < N - K + 1; i++) { + for (let j = 0; j < N - K + 1; j++) { + min_result = Math.min(min_result, getTrashCount(data, i, j, K)); + } + } + console.log(min_result); +}; + +const readline = require('readline'); + +(async () => { + let rl = readline.createInterface({ input: process.stdin }); + + let T = null; + let info = null; // N, K + let data = []; + let count_T = 0; + let count_N = 0; + for await (const line of rl) { + if (!T) { + T = +line; + } else if (T && !info) { + info = line.split(' ').map((el) => +el); + } else { + data.push(line.split(' ').map((el) => +el)); + count_N += 1; + } + if (T && info) { + if (info[0] === count_N) { + // 로직 수행 & 초기화 + print(data); + solution(data, info); + + info = null; // N, K + data = []; + count_T = 0; + count_N = 0; + } + } + } + + // rl.close(); + + process.exit(); +})(); diff --git a/src/grap3fruit/goorm/input.js b/src/grap3fruit/goorm/input.js new file mode 100644 index 0000000..dc5cb8e --- /dev/null +++ b/src/grap3fruit/goorm/input.js @@ -0,0 +1,33 @@ +const print = (N, data) => { + console.log(N); + console.log(data); +}; + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let N = null; +let count = 0; +const data = []; + +rl.on('line', function (line) { + console.log(line); + if (!N) { + N = +line; + } else { + // data.push(line.split(' ').map((el) => +el)); + // data.push(line.split('').map((el) => +el)); + // data.push(line.split('').map((el) => el)); + data.push(line); + } + count += 1; + if (count === N) { + rl.close(); + } +}).on('close', function () { + print(N, data); + process.exit(); +}); diff --git a/src/grap3fruit/goorm/input1_2.js b/src/grap3fruit/goorm/input1_2.js new file mode 100644 index 0000000..9577ac4 --- /dev/null +++ b/src/grap3fruit/goorm/input1_2.js @@ -0,0 +1,37 @@ +const print = (N, info, data) => { + console.log(N); + console.log(info); + console.log(data); +}; + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let N = null; +let info = null; +let count = 0; +const data = []; + +rl.on('line', function (line) { + console.log(line); + if (!N) { + N = +line; + } else if (N && !info) { + info = line.split(' ').map((el) => +el); + } else { + data.push(line.split(' ').map((el) => +el)); + // data.push(line.split('').map((el) => +el)); + // data.push(line.split('').map((el) => el)); + // data.push(line); + count += 1; + } + if (count === N) { + rl.close(); + } +}).on('close', function () { + print(N, info, data); + process.exit(); +}); diff --git a/src/grap3fruit/goorm/input2.js b/src/grap3fruit/goorm/input2.js new file mode 100644 index 0000000..e3b2161 --- /dev/null +++ b/src/grap3fruit/goorm/input2.js @@ -0,0 +1,33 @@ +const print = (N, data) => { + console.log(N); + console.log(data); +}; + +const readline = require('readline'); + +(async () => { + let rl = readline.createInterface({ input: process.stdin }); + let N = null; + let count = 0; + const data = []; + + for await (const line of rl) { + if (!N) { + N = +line; + } else { + data.push(line.split('').map((el) => +el)); + // data.push(line); + count += 1; + } + if (N === count) { + rl.close(); + } + } + + data.forEach((el) => { + console.log('len: ', el.length); + }); + + print(N, data); + process.exit(); +})(); From 1504ae4ac371761f40c5b4b5975efeb6d56512e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B6=8C=EC=98=81=EC=96=B8?= Date: Sat, 2 Jan 2021 18:04:20 +0900 Subject: [PATCH 167/193] =?UTF-8?q?docs:=2015=EC=A3=BC=EC=B0=A8=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=97=85=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 42a67d8..ff99bcb 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ | 12주차 | [ATM](https://www.acmicpc.net/problem/11399) | [회문](https://www.acmicpc.net/problem/17609) | | | | 13주차 | [미로탐색](https://www.acmicpc.net/problem/2178) | [암호코드](https://www.acmicpc.net/problem/2011) | [떡먹는호랑이](https://www.acmicpc.net/problem/2502) | [촌수계산](https://www.acmicpc.net/problem/2644) | | 14주차 | [크레인 인형뽑기](https://programmers.co.kr/learn/courses/30/lessons/64061) | [가장 긴 팰린드롬](https://programmers.co.kr/learn/courses/30/lessons/12904) | [튜플](https://programmers.co.kr/learn/courses/30/lessons/64065) | | - +| 15주차 | [위장](https://programmers.co.kr/learn/courses/30/lessons/42578) | [네트워크](https://programmers.co.kr/learn/courses/30/lessons/43162) | [영어 끝말잇기](https://programmers.co.kr/learn/courses/30/lessons/12981) | | ## :blue_book: Additional Study | 분류 | | | | From 94933b3da438a40e4c4ef5227f1621736f15a757 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Sun, 3 Jan 2021 22:25:38 +0900 Subject: [PATCH 168/193] =?UTF-8?q?[refactor]=20py,js=20=ED=8F=B4=EB=8D=94?= =?UTF-8?q?=EB=A1=9C=20=EB=82=98=EB=88=84=EA=B3=A0=20=ED=95=98=EC=9C=84?= =?UTF-8?q?=EC=97=90=20=EC=BD=94=ED=85=8C=20=EC=82=AC=EC=9D=B4=ED=8A=B8=20?= =?UTF-8?q?=EB=91=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/goorm/43089.js | 27 ------- src/grap3fruit/goorm/43125.js | 29 ------- src/grap3fruit/goorm/88520.js | 64 --------------- .../{goorm/input.js => js/goorm/input1.js} | 0 src/grap3fruit/js/goorm/input1.md | 0 src/grap3fruit/{ => js}/goorm/input1_2.js | 4 +- src/grap3fruit/{ => js}/goorm/input2.js | 14 ++-- src/grap3fruit/js/goorm/input2.md | 61 +++++++++++++++ .../js => js/programmers}/12904.js | 0 .../js => js/programmers}/12904.md | 0 .../js => js/programmers}/64061.js | 0 .../js => js/programmers}/64061.md | 0 .../js => js/programmers}/64061_2.js | 0 .../js => js/programmers}/64065.js | 0 .../js => js/programmers}/64065.md | 0 src/grap3fruit/{ => py}/boj/1010.md | 0 src/grap3fruit/{ => py}/boj/1010.py | 0 src/grap3fruit/{ => py}/boj/1094.md | 0 src/grap3fruit/{ => py}/boj/1094.py | 0 src/grap3fruit/{ => py}/boj/11047.md | 0 src/grap3fruit/{ => py}/boj/11047.py | 0 src/grap3fruit/{ => py}/boj/11286.py | 78 +++++++++---------- src/grap3fruit/{ => py}/boj/11399.md | 0 src/grap3fruit/{ => py}/boj/11399.py | 0 src/grap3fruit/{ => py}/boj/1149.md | 0 src/grap3fruit/{ => py}/boj/1149.py | 0 src/grap3fruit/{ => py}/boj/11497.md | 0 src/grap3fruit/{ => py}/boj/11497.py | 0 src/grap3fruit/{ => py}/boj/11727.md | 0 src/grap3fruit/{ => py}/boj/11727.py | 0 src/grap3fruit/{ => py}/boj/1254.md | 0 src/grap3fruit/{ => py}/boj/1254.py | 0 src/grap3fruit/{ => py}/boj/12731.md | 0 src/grap3fruit/{ => py}/boj/12731.py | 0 src/grap3fruit/{ => py}/boj/1316.py | 0 src/grap3fruit/{ => py}/boj/14889.md | 0 src/grap3fruit/{ => py}/boj/14889.py | 0 src/grap3fruit/{ => py}/boj/1697.md | 0 src/grap3fruit/{ => py}/boj/1697.py | 0 src/grap3fruit/{ => py}/boj/17609.md | 0 src/grap3fruit/{ => py}/boj/17609.py | 0 src/grap3fruit/{ => py}/boj/18233.md | 0 src/grap3fruit/{ => py}/boj/18233.py | 0 src/grap3fruit/{ => py}/boj/19238.py | 0 src/grap3fruit/{ => py}/boj/1932.md | 0 src/grap3fruit/{ => py}/boj/1932.py | 0 src/grap3fruit/{ => py}/boj/1946.md | 0 src/grap3fruit/{ => py}/boj/1946.py | 0 src/grap3fruit/{ => py}/boj/1991.py | 0 src/grap3fruit/{ => py}/boj/2011.md | 0 src/grap3fruit/{ => py}/boj/2011.py | 0 src/grap3fruit/{ => py}/boj/2178.md | 0 src/grap3fruit/{ => py}/boj/2178.py | 0 src/grap3fruit/{ => py}/boj/2502.md | 0 src/grap3fruit/{ => py}/boj/2502.py | 0 src/grap3fruit/{ => py}/boj/2579.md | 0 src/grap3fruit/{ => py}/boj/2579.py | 0 src/grap3fruit/{ => py}/boj/2606.md | 0 src/grap3fruit/{ => py}/boj/2606.py | 0 src/grap3fruit/{ => py}/boj/2644.md | 0 src/grap3fruit/{ => py}/boj/2644.py | 0 src/grap3fruit/{ => py}/boj/2957.py | 0 src/grap3fruit/{ => py}/boj/7569.md | 0 src/grap3fruit/{ => py}/boj/7569.py | 0 src/grap3fruit/{ => py}/boj/9095.md | 0 src/grap3fruit/{ => py}/boj/9095.py | 0 src/grap3fruit/{ => py}/input_test.py | 0 .../py => py/programmers}/17685.py | 0 .../py => py/programmers}/42578.py | 0 .../py => py/programmers}/60057.py | 0 70 files changed, 108 insertions(+), 169 deletions(-) delete mode 100644 src/grap3fruit/goorm/43089.js delete mode 100644 src/grap3fruit/goorm/43125.js delete mode 100644 src/grap3fruit/goorm/88520.js rename src/grap3fruit/{goorm/input.js => js/goorm/input1.js} (100%) create mode 100644 src/grap3fruit/js/goorm/input1.md rename src/grap3fruit/{ => js}/goorm/input1_2.js (91%) rename src/grap3fruit/{ => js}/goorm/input2.js (52%) create mode 100644 src/grap3fruit/js/goorm/input2.md rename src/grap3fruit/{programmers/js => js/programmers}/12904.js (100%) rename src/grap3fruit/{programmers/js => js/programmers}/12904.md (100%) rename src/grap3fruit/{programmers/js => js/programmers}/64061.js (100%) rename src/grap3fruit/{programmers/js => js/programmers}/64061.md (100%) rename src/grap3fruit/{programmers/js => js/programmers}/64061_2.js (100%) rename src/grap3fruit/{programmers/js => js/programmers}/64065.js (100%) rename src/grap3fruit/{programmers/js => js/programmers}/64065.md (100%) rename src/grap3fruit/{ => py}/boj/1010.md (100%) rename src/grap3fruit/{ => py}/boj/1010.py (100%) rename src/grap3fruit/{ => py}/boj/1094.md (100%) rename src/grap3fruit/{ => py}/boj/1094.py (100%) rename src/grap3fruit/{ => py}/boj/11047.md (100%) rename src/grap3fruit/{ => py}/boj/11047.py (100%) rename src/grap3fruit/{ => py}/boj/11286.py (92%) rename src/grap3fruit/{ => py}/boj/11399.md (100%) rename src/grap3fruit/{ => py}/boj/11399.py (100%) rename src/grap3fruit/{ => py}/boj/1149.md (100%) rename src/grap3fruit/{ => py}/boj/1149.py (100%) rename src/grap3fruit/{ => py}/boj/11497.md (100%) rename src/grap3fruit/{ => py}/boj/11497.py (100%) rename src/grap3fruit/{ => py}/boj/11727.md (100%) rename src/grap3fruit/{ => py}/boj/11727.py (100%) rename src/grap3fruit/{ => py}/boj/1254.md (100%) rename src/grap3fruit/{ => py}/boj/1254.py (100%) rename src/grap3fruit/{ => py}/boj/12731.md (100%) rename src/grap3fruit/{ => py}/boj/12731.py (100%) rename src/grap3fruit/{ => py}/boj/1316.py (100%) rename src/grap3fruit/{ => py}/boj/14889.md (100%) rename src/grap3fruit/{ => py}/boj/14889.py (100%) rename src/grap3fruit/{ => py}/boj/1697.md (100%) rename src/grap3fruit/{ => py}/boj/1697.py (100%) rename src/grap3fruit/{ => py}/boj/17609.md (100%) rename src/grap3fruit/{ => py}/boj/17609.py (100%) rename src/grap3fruit/{ => py}/boj/18233.md (100%) rename src/grap3fruit/{ => py}/boj/18233.py (100%) rename src/grap3fruit/{ => py}/boj/19238.py (100%) rename src/grap3fruit/{ => py}/boj/1932.md (100%) rename src/grap3fruit/{ => py}/boj/1932.py (100%) rename src/grap3fruit/{ => py}/boj/1946.md (100%) rename src/grap3fruit/{ => py}/boj/1946.py (100%) rename src/grap3fruit/{ => py}/boj/1991.py (100%) rename src/grap3fruit/{ => py}/boj/2011.md (100%) rename src/grap3fruit/{ => py}/boj/2011.py (100%) rename src/grap3fruit/{ => py}/boj/2178.md (100%) rename src/grap3fruit/{ => py}/boj/2178.py (100%) rename src/grap3fruit/{ => py}/boj/2502.md (100%) rename src/grap3fruit/{ => py}/boj/2502.py (100%) rename src/grap3fruit/{ => py}/boj/2579.md (100%) rename src/grap3fruit/{ => py}/boj/2579.py (100%) rename src/grap3fruit/{ => py}/boj/2606.md (100%) rename src/grap3fruit/{ => py}/boj/2606.py (100%) rename src/grap3fruit/{ => py}/boj/2644.md (100%) rename src/grap3fruit/{ => py}/boj/2644.py (100%) rename src/grap3fruit/{ => py}/boj/2957.py (100%) rename src/grap3fruit/{ => py}/boj/7569.md (100%) rename src/grap3fruit/{ => py}/boj/7569.py (100%) rename src/grap3fruit/{ => py}/boj/9095.md (100%) rename src/grap3fruit/{ => py}/boj/9095.py (100%) rename src/grap3fruit/{ => py}/input_test.py (100%) rename src/grap3fruit/{programmers/py => py/programmers}/17685.py (100%) rename src/grap3fruit/{programmers/py => py/programmers}/42578.py (100%) rename src/grap3fruit/{programmers/py => py/programmers}/60057.py (100%) diff --git a/src/grap3fruit/goorm/43089.js b/src/grap3fruit/goorm/43089.js deleted file mode 100644 index 26169ca..0000000 --- a/src/grap3fruit/goorm/43089.js +++ /dev/null @@ -1,27 +0,0 @@ -// Run by Node.js -const getResultLength = (data) => { - dataArr = data[0].split(''); - // console.log(dataArr) - const result = dataArr.filter((el) => el === data[1]); - return result.length; -}; - -const readline = require('readline'); -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); - -let count = 0; -let n = 2; -data = []; -rl.on('line', function (line) { - data.push(line); - count += 1; - if (count === n) { - rl.close(); - } -}).on('close', function () { - console.log(getResultLength(data)); - process.exit(); -}); diff --git a/src/grap3fruit/goorm/43125.js b/src/grap3fruit/goorm/43125.js deleted file mode 100644 index 9087227..0000000 --- a/src/grap3fruit/goorm/43125.js +++ /dev/null @@ -1,29 +0,0 @@ -// Run by Node.js - -const readline = require('readline'); -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); - -let N = 0; -// const data = []; -let count = 0; - -rl.on('line', function (line) { - if (!N) { - N = +line; - } else { - const data = line.split(' ').map((el) => +el); - let min = data[0]; - for (let i = 1; i < data.length; i++) { - if (data[i] < min) { - min = data[i]; - } - } - console.log(min); - rl.close(); - } -}).on('close', function () { - process.exit(); -}); diff --git a/src/grap3fruit/goorm/88520.js b/src/grap3fruit/goorm/88520.js deleted file mode 100644 index cb71b2c..0000000 --- a/src/grap3fruit/goorm/88520.js +++ /dev/null @@ -1,64 +0,0 @@ -const print = (data) => { - console.log(data); -}; - -const getTrashCount = (data, A, B, K) => { - let count = 0; - for (let i = A; i < A + K; i++) { - for (let j = B; j < B + K; j++) { - if (data[i][j] === 1) { - count += 1; - } - } - } - return count; -}; - -const solution = (data, info) => { - const [N, K] = info; - let min_result = K * K; - for (let i = 0; i < N - K + 1; i++) { - for (let j = 0; j < N - K + 1; j++) { - min_result = Math.min(min_result, getTrashCount(data, i, j, K)); - } - } - console.log(min_result); -}; - -const readline = require('readline'); - -(async () => { - let rl = readline.createInterface({ input: process.stdin }); - - let T = null; - let info = null; // N, K - let data = []; - let count_T = 0; - let count_N = 0; - for await (const line of rl) { - if (!T) { - T = +line; - } else if (T && !info) { - info = line.split(' ').map((el) => +el); - } else { - data.push(line.split(' ').map((el) => +el)); - count_N += 1; - } - if (T && info) { - if (info[0] === count_N) { - // 로직 수행 & 초기화 - print(data); - solution(data, info); - - info = null; // N, K - data = []; - count_T = 0; - count_N = 0; - } - } - } - - // rl.close(); - - process.exit(); -})(); diff --git a/src/grap3fruit/goorm/input.js b/src/grap3fruit/js/goorm/input1.js similarity index 100% rename from src/grap3fruit/goorm/input.js rename to src/grap3fruit/js/goorm/input1.js diff --git a/src/grap3fruit/js/goorm/input1.md b/src/grap3fruit/js/goorm/input1.md new file mode 100644 index 0000000..e69de29 diff --git a/src/grap3fruit/goorm/input1_2.js b/src/grap3fruit/js/goorm/input1_2.js similarity index 91% rename from src/grap3fruit/goorm/input1_2.js rename to src/grap3fruit/js/goorm/input1_2.js index 9577ac4..44c143c 100644 --- a/src/grap3fruit/goorm/input1_2.js +++ b/src/grap3fruit/js/goorm/input1_2.js @@ -1,4 +1,4 @@ -const print = (N, info, data) => { +const solution = (N, info, data) => { console.log(N); console.log(info); console.log(data); @@ -32,6 +32,6 @@ rl.on('line', function (line) { rl.close(); } }).on('close', function () { - print(N, info, data); + solution(N, info, data); process.exit(); }); diff --git a/src/grap3fruit/goorm/input2.js b/src/grap3fruit/js/goorm/input2.js similarity index 52% rename from src/grap3fruit/goorm/input2.js rename to src/grap3fruit/js/goorm/input2.js index e3b2161..ecd6f81 100644 --- a/src/grap3fruit/goorm/input2.js +++ b/src/grap3fruit/js/goorm/input2.js @@ -1,4 +1,4 @@ -const print = (N, data) => { +const solution = (N, data) => { console.log(N); console.log(data); }; @@ -15,8 +15,10 @@ const readline = require('readline'); if (!N) { N = +line; } else { - data.push(line.split('').map((el) => +el)); - // data.push(line); + // data.push(line); // 1 2 3 4 5 -> ['1 2 3 4 5'] + // data.push(line.split(' ').map((el) => +el)); // 1 2 3 4 5 -> [1,2,3,4,5] + // data.push(line.split('').map((el) => el)); // 12345 -> ['1','2','3','4','5'] + data.push(line.split('').map((el) => +el)); // 12345 -> [1,2,3,4,5] count += 1; } if (N === count) { @@ -24,10 +26,6 @@ const readline = require('readline'); } } - data.forEach((el) => { - console.log('len: ', el.length); - }); - - print(N, data); + solution(N, data); process.exit(); })(); diff --git a/src/grap3fruit/js/goorm/input2.md b/src/grap3fruit/js/goorm/input2.md new file mode 100644 index 0000000..cb7eff6 --- /dev/null +++ b/src/grap3fruit/js/goorm/input2.md @@ -0,0 +1,61 @@ +test case + +``` +5 +12345 +23456 +34567 +45678 +56789 +``` + +결과 + +``` +5 +[ + [1,2,3,4,5], + [2,3,4,5,6], + [3,4,5,6,7], + [4,5,6,7,8], + [5,6,7,8,9] +] +``` + +```javascript +const print = (N, data) => { + console.log(N); + console.log(data); +}; + +const readline = require('readline'); + +(async () => { + let rl = readline.createInterface({ input: process.stdin }); + let N = null; + let count = 0; + const data = []; + + for await (const line of rl) { + if (!N) { + N = +line; + } else { + // data.push(line); // 1 2 3 4 5 -> ['1 2 3 4 5'] + // data.push(line.split(' ').map((el) => +el)); // 1 2 3 4 5 -> [1,2,3,4,5] + // data.push(line.split('').map((el) => el)); // 12345 -> ['1','2','3','4','5'] + data.push(line.split('').map((el) => +el)); // 12345 -> [1,2,3,4,5] + count += 1; + } + if (N === count) { + rl.close(); + } + } + + data.forEach((el) => { + console.log('len: ', el.length); + }); + + print(N, data); + process.exit(); +})(); +``` diff --git a/src/grap3fruit/programmers/js/12904.js b/src/grap3fruit/js/programmers/12904.js similarity index 100% rename from src/grap3fruit/programmers/js/12904.js rename to src/grap3fruit/js/programmers/12904.js diff --git a/src/grap3fruit/programmers/js/12904.md b/src/grap3fruit/js/programmers/12904.md similarity index 100% rename from src/grap3fruit/programmers/js/12904.md rename to src/grap3fruit/js/programmers/12904.md diff --git a/src/grap3fruit/programmers/js/64061.js b/src/grap3fruit/js/programmers/64061.js similarity index 100% rename from src/grap3fruit/programmers/js/64061.js rename to src/grap3fruit/js/programmers/64061.js diff --git a/src/grap3fruit/programmers/js/64061.md b/src/grap3fruit/js/programmers/64061.md similarity index 100% rename from src/grap3fruit/programmers/js/64061.md rename to src/grap3fruit/js/programmers/64061.md diff --git a/src/grap3fruit/programmers/js/64061_2.js b/src/grap3fruit/js/programmers/64061_2.js similarity index 100% rename from src/grap3fruit/programmers/js/64061_2.js rename to src/grap3fruit/js/programmers/64061_2.js diff --git a/src/grap3fruit/programmers/js/64065.js b/src/grap3fruit/js/programmers/64065.js similarity index 100% rename from src/grap3fruit/programmers/js/64065.js rename to src/grap3fruit/js/programmers/64065.js diff --git a/src/grap3fruit/programmers/js/64065.md b/src/grap3fruit/js/programmers/64065.md similarity index 100% rename from src/grap3fruit/programmers/js/64065.md rename to src/grap3fruit/js/programmers/64065.md diff --git a/src/grap3fruit/boj/1010.md b/src/grap3fruit/py/boj/1010.md similarity index 100% rename from src/grap3fruit/boj/1010.md rename to src/grap3fruit/py/boj/1010.md diff --git a/src/grap3fruit/boj/1010.py b/src/grap3fruit/py/boj/1010.py similarity index 100% rename from src/grap3fruit/boj/1010.py rename to src/grap3fruit/py/boj/1010.py diff --git a/src/grap3fruit/boj/1094.md b/src/grap3fruit/py/boj/1094.md similarity index 100% rename from src/grap3fruit/boj/1094.md rename to src/grap3fruit/py/boj/1094.md diff --git a/src/grap3fruit/boj/1094.py b/src/grap3fruit/py/boj/1094.py similarity index 100% rename from src/grap3fruit/boj/1094.py rename to src/grap3fruit/py/boj/1094.py diff --git a/src/grap3fruit/boj/11047.md b/src/grap3fruit/py/boj/11047.md similarity index 100% rename from src/grap3fruit/boj/11047.md rename to src/grap3fruit/py/boj/11047.md diff --git a/src/grap3fruit/boj/11047.py b/src/grap3fruit/py/boj/11047.py similarity index 100% rename from src/grap3fruit/boj/11047.py rename to src/grap3fruit/py/boj/11047.py diff --git a/src/grap3fruit/boj/11286.py b/src/grap3fruit/py/boj/11286.py similarity index 92% rename from src/grap3fruit/boj/11286.py rename to src/grap3fruit/py/boj/11286.py index 690cae3..35748d4 100644 --- a/src/grap3fruit/boj/11286.py +++ b/src/grap3fruit/py/boj/11286.py @@ -1,39 +1,39 @@ -import heapq -import sys - -# n = 18 -# x = [1, -# -1, -# 0, -# 0, -# 0, -# 1, -# 1, -# -1, -# -1, -# 2, -# -2, -# 0, -# 0, -# 0, -# 0, -# 0, -# 0, -# 0] - -n = int(sys.stdin.readline().strip()) -heap = [] -x = [] -for i in range(0, n): - x.append(int(sys.stdin.readline().strip())) - -for i in range(0,n): - if x[i] == 0: - if len(heap) == 0: - print(0) - continue - - print(heapq.heappop(heap)[1]) - continue - if x[i] != 0: - heapq.heappush(heap,(abs(x[i]),x[i])) +import heapq +import sys + +# n = 18 +# x = [1, +# -1, +# 0, +# 0, +# 0, +# 1, +# 1, +# -1, +# -1, +# 2, +# -2, +# 0, +# 0, +# 0, +# 0, +# 0, +# 0, +# 0] + +n = int(sys.stdin.readline().strip()) +heap = [] +x = [] +for i in range(0, n): + x.append(int(sys.stdin.readline().strip())) + +for i in range(0,n): + if x[i] == 0: + if len(heap) == 0: + print(0) + continue + + print(heapq.heappop(heap)[1]) + continue + if x[i] != 0: + heapq.heappush(heap,(abs(x[i]),x[i])) diff --git a/src/grap3fruit/boj/11399.md b/src/grap3fruit/py/boj/11399.md similarity index 100% rename from src/grap3fruit/boj/11399.md rename to src/grap3fruit/py/boj/11399.md diff --git a/src/grap3fruit/boj/11399.py b/src/grap3fruit/py/boj/11399.py similarity index 100% rename from src/grap3fruit/boj/11399.py rename to src/grap3fruit/py/boj/11399.py diff --git a/src/grap3fruit/boj/1149.md b/src/grap3fruit/py/boj/1149.md similarity index 100% rename from src/grap3fruit/boj/1149.md rename to src/grap3fruit/py/boj/1149.md diff --git a/src/grap3fruit/boj/1149.py b/src/grap3fruit/py/boj/1149.py similarity index 100% rename from src/grap3fruit/boj/1149.py rename to src/grap3fruit/py/boj/1149.py diff --git a/src/grap3fruit/boj/11497.md b/src/grap3fruit/py/boj/11497.md similarity index 100% rename from src/grap3fruit/boj/11497.md rename to src/grap3fruit/py/boj/11497.md diff --git a/src/grap3fruit/boj/11497.py b/src/grap3fruit/py/boj/11497.py similarity index 100% rename from src/grap3fruit/boj/11497.py rename to src/grap3fruit/py/boj/11497.py diff --git a/src/grap3fruit/boj/11727.md b/src/grap3fruit/py/boj/11727.md similarity index 100% rename from src/grap3fruit/boj/11727.md rename to src/grap3fruit/py/boj/11727.md diff --git a/src/grap3fruit/boj/11727.py b/src/grap3fruit/py/boj/11727.py similarity index 100% rename from src/grap3fruit/boj/11727.py rename to src/grap3fruit/py/boj/11727.py diff --git a/src/grap3fruit/boj/1254.md b/src/grap3fruit/py/boj/1254.md similarity index 100% rename from src/grap3fruit/boj/1254.md rename to src/grap3fruit/py/boj/1254.md diff --git a/src/grap3fruit/boj/1254.py b/src/grap3fruit/py/boj/1254.py similarity index 100% rename from src/grap3fruit/boj/1254.py rename to src/grap3fruit/py/boj/1254.py diff --git a/src/grap3fruit/boj/12731.md b/src/grap3fruit/py/boj/12731.md similarity index 100% rename from src/grap3fruit/boj/12731.md rename to src/grap3fruit/py/boj/12731.md diff --git a/src/grap3fruit/boj/12731.py b/src/grap3fruit/py/boj/12731.py similarity index 100% rename from src/grap3fruit/boj/12731.py rename to src/grap3fruit/py/boj/12731.py diff --git a/src/grap3fruit/boj/1316.py b/src/grap3fruit/py/boj/1316.py similarity index 100% rename from src/grap3fruit/boj/1316.py rename to src/grap3fruit/py/boj/1316.py diff --git a/src/grap3fruit/boj/14889.md b/src/grap3fruit/py/boj/14889.md similarity index 100% rename from src/grap3fruit/boj/14889.md rename to src/grap3fruit/py/boj/14889.md diff --git a/src/grap3fruit/boj/14889.py b/src/grap3fruit/py/boj/14889.py similarity index 100% rename from src/grap3fruit/boj/14889.py rename to src/grap3fruit/py/boj/14889.py diff --git a/src/grap3fruit/boj/1697.md b/src/grap3fruit/py/boj/1697.md similarity index 100% rename from src/grap3fruit/boj/1697.md rename to src/grap3fruit/py/boj/1697.md diff --git a/src/grap3fruit/boj/1697.py b/src/grap3fruit/py/boj/1697.py similarity index 100% rename from src/grap3fruit/boj/1697.py rename to src/grap3fruit/py/boj/1697.py diff --git a/src/grap3fruit/boj/17609.md b/src/grap3fruit/py/boj/17609.md similarity index 100% rename from src/grap3fruit/boj/17609.md rename to src/grap3fruit/py/boj/17609.md diff --git a/src/grap3fruit/boj/17609.py b/src/grap3fruit/py/boj/17609.py similarity index 100% rename from src/grap3fruit/boj/17609.py rename to src/grap3fruit/py/boj/17609.py diff --git a/src/grap3fruit/boj/18233.md b/src/grap3fruit/py/boj/18233.md similarity index 100% rename from src/grap3fruit/boj/18233.md rename to src/grap3fruit/py/boj/18233.md diff --git a/src/grap3fruit/boj/18233.py b/src/grap3fruit/py/boj/18233.py similarity index 100% rename from src/grap3fruit/boj/18233.py rename to src/grap3fruit/py/boj/18233.py diff --git a/src/grap3fruit/boj/19238.py b/src/grap3fruit/py/boj/19238.py similarity index 100% rename from src/grap3fruit/boj/19238.py rename to src/grap3fruit/py/boj/19238.py diff --git a/src/grap3fruit/boj/1932.md b/src/grap3fruit/py/boj/1932.md similarity index 100% rename from src/grap3fruit/boj/1932.md rename to src/grap3fruit/py/boj/1932.md diff --git a/src/grap3fruit/boj/1932.py b/src/grap3fruit/py/boj/1932.py similarity index 100% rename from src/grap3fruit/boj/1932.py rename to src/grap3fruit/py/boj/1932.py diff --git a/src/grap3fruit/boj/1946.md b/src/grap3fruit/py/boj/1946.md similarity index 100% rename from src/grap3fruit/boj/1946.md rename to src/grap3fruit/py/boj/1946.md diff --git a/src/grap3fruit/boj/1946.py b/src/grap3fruit/py/boj/1946.py similarity index 100% rename from src/grap3fruit/boj/1946.py rename to src/grap3fruit/py/boj/1946.py diff --git a/src/grap3fruit/boj/1991.py b/src/grap3fruit/py/boj/1991.py similarity index 100% rename from src/grap3fruit/boj/1991.py rename to src/grap3fruit/py/boj/1991.py diff --git a/src/grap3fruit/boj/2011.md b/src/grap3fruit/py/boj/2011.md similarity index 100% rename from src/grap3fruit/boj/2011.md rename to src/grap3fruit/py/boj/2011.md diff --git a/src/grap3fruit/boj/2011.py b/src/grap3fruit/py/boj/2011.py similarity index 100% rename from src/grap3fruit/boj/2011.py rename to src/grap3fruit/py/boj/2011.py diff --git a/src/grap3fruit/boj/2178.md b/src/grap3fruit/py/boj/2178.md similarity index 100% rename from src/grap3fruit/boj/2178.md rename to src/grap3fruit/py/boj/2178.md diff --git a/src/grap3fruit/boj/2178.py b/src/grap3fruit/py/boj/2178.py similarity index 100% rename from src/grap3fruit/boj/2178.py rename to src/grap3fruit/py/boj/2178.py diff --git a/src/grap3fruit/boj/2502.md b/src/grap3fruit/py/boj/2502.md similarity index 100% rename from src/grap3fruit/boj/2502.md rename to src/grap3fruit/py/boj/2502.md diff --git a/src/grap3fruit/boj/2502.py b/src/grap3fruit/py/boj/2502.py similarity index 100% rename from src/grap3fruit/boj/2502.py rename to src/grap3fruit/py/boj/2502.py diff --git a/src/grap3fruit/boj/2579.md b/src/grap3fruit/py/boj/2579.md similarity index 100% rename from src/grap3fruit/boj/2579.md rename to src/grap3fruit/py/boj/2579.md diff --git a/src/grap3fruit/boj/2579.py b/src/grap3fruit/py/boj/2579.py similarity index 100% rename from src/grap3fruit/boj/2579.py rename to src/grap3fruit/py/boj/2579.py diff --git a/src/grap3fruit/boj/2606.md b/src/grap3fruit/py/boj/2606.md similarity index 100% rename from src/grap3fruit/boj/2606.md rename to src/grap3fruit/py/boj/2606.md diff --git a/src/grap3fruit/boj/2606.py b/src/grap3fruit/py/boj/2606.py similarity index 100% rename from src/grap3fruit/boj/2606.py rename to src/grap3fruit/py/boj/2606.py diff --git a/src/grap3fruit/boj/2644.md b/src/grap3fruit/py/boj/2644.md similarity index 100% rename from src/grap3fruit/boj/2644.md rename to src/grap3fruit/py/boj/2644.md diff --git a/src/grap3fruit/boj/2644.py b/src/grap3fruit/py/boj/2644.py similarity index 100% rename from src/grap3fruit/boj/2644.py rename to src/grap3fruit/py/boj/2644.py diff --git a/src/grap3fruit/boj/2957.py b/src/grap3fruit/py/boj/2957.py similarity index 100% rename from src/grap3fruit/boj/2957.py rename to src/grap3fruit/py/boj/2957.py diff --git a/src/grap3fruit/boj/7569.md b/src/grap3fruit/py/boj/7569.md similarity index 100% rename from src/grap3fruit/boj/7569.md rename to src/grap3fruit/py/boj/7569.md diff --git a/src/grap3fruit/boj/7569.py b/src/grap3fruit/py/boj/7569.py similarity index 100% rename from src/grap3fruit/boj/7569.py rename to src/grap3fruit/py/boj/7569.py diff --git a/src/grap3fruit/boj/9095.md b/src/grap3fruit/py/boj/9095.md similarity index 100% rename from src/grap3fruit/boj/9095.md rename to src/grap3fruit/py/boj/9095.md diff --git a/src/grap3fruit/boj/9095.py b/src/grap3fruit/py/boj/9095.py similarity index 100% rename from src/grap3fruit/boj/9095.py rename to src/grap3fruit/py/boj/9095.py diff --git a/src/grap3fruit/input_test.py b/src/grap3fruit/py/input_test.py similarity index 100% rename from src/grap3fruit/input_test.py rename to src/grap3fruit/py/input_test.py diff --git a/src/grap3fruit/programmers/py/17685.py b/src/grap3fruit/py/programmers/17685.py similarity index 100% rename from src/grap3fruit/programmers/py/17685.py rename to src/grap3fruit/py/programmers/17685.py diff --git a/src/grap3fruit/programmers/py/42578.py b/src/grap3fruit/py/programmers/42578.py similarity index 100% rename from src/grap3fruit/programmers/py/42578.py rename to src/grap3fruit/py/programmers/42578.py diff --git a/src/grap3fruit/programmers/py/60057.py b/src/grap3fruit/py/programmers/60057.py similarity index 100% rename from src/grap3fruit/programmers/py/60057.py rename to src/grap3fruit/py/programmers/60057.py From 3cabe485e5cc8a7740aba4b956091c8289d763a4 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Sun, 3 Jan 2021 23:13:01 +0900 Subject: [PATCH 169/193] =?UTF-8?q?solve=20:=20programmers=20=EC=9C=84?= =?UTF-8?q?=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week15.md | 7 +++++++ src/do02reen24/etc/programmers_42578.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/do02reen24/Review/week15.md create mode 100644 src/do02reen24/etc/programmers_42578.js diff --git a/src/do02reen24/Review/week15.md b/src/do02reen24/Review/week15.md new file mode 100644 index 0000000..7b70f0d --- /dev/null +++ b/src/do02reen24/Review/week15.md @@ -0,0 +1,7 @@ +# :fire: week15 + +## :ballot_box_with_check: 프로그래머스 위장(42578) + +- 조합의 개념을 사용하여 풀 수 있었다. +- 해당 옷을 아예 고르지 않는 경우도 있으므로 각 아이템 길이에 + 1 을 해주었다. +- 모든 옷을 안고르는 경우는 제외해야하므로 정답에서 - 1 을 해주었다. diff --git a/src/do02reen24/etc/programmers_42578.js b/src/do02reen24/etc/programmers_42578.js new file mode 100644 index 0000000..39d57b9 --- /dev/null +++ b/src/do02reen24/etc/programmers_42578.js @@ -0,0 +1,19 @@ +const getCombinationNumber = (object) => { + let combination = 1; + for (const key in object) { + const itemLength = object[key].length + 1; + combination *= itemLength; + } + return combination; +}; + +const solution = (clothes) => { + const closet = {}; + clothes.forEach(([cloth, clothType]) => { + closet[clothType] + ? closet[clothType].push(cloth) + : (closet[clothType] = [cloth]); + }); + + return getCombinationNumber(closet) - 1; +}; From 3dbc38466184f765ee6f04c756573ed0a19bf813 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Mon, 4 Jan 2021 15:25:04 +0900 Subject: [PATCH 170/193] =?UTF-8?q?solve=20:=20programmers=20=EC=98=81?= =?UTF-8?q?=EC=96=B4=20=EB=81=9D=EB=A7=90=EC=9E=87=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/Review/week15.md | 4 ++++ src/do02reen24/programmers_12981.js | 31 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/do02reen24/programmers_12981.js diff --git a/src/do02reen24/Review/week15.md b/src/do02reen24/Review/week15.md index 7b70f0d..0363baf 100644 --- a/src/do02reen24/Review/week15.md +++ b/src/do02reen24/Review/week15.md @@ -5,3 +5,7 @@ - 조합의 개념을 사용하여 풀 수 있었다. - 해당 옷을 아예 고르지 않는 경우도 있으므로 각 아이템 길이에 + 1 을 해주었다. - 모든 옷을 안고르는 경우는 제외해야하므로 정답에서 - 1 을 해주었다. + +## :ballot_box_with_check: 프로그래머스 영어 끝말잇기(12981) + +- 각 경우를 고려하여 처리해주었다. diff --git a/src/do02reen24/programmers_12981.js b/src/do02reen24/programmers_12981.js new file mode 100644 index 0000000..2b31345 --- /dev/null +++ b/src/do02reen24/programmers_12981.js @@ -0,0 +1,31 @@ +const failUser = (n, index) => { + let person = index % n; + let order = Math.floor(index / n) + 1; + if (person === 0) { + person = n; + order -= 1; + } + return [person, order]; +}; + +const getLastChar = (word) => word.charAt(word.length - 1); + +const solution = (n, words) => { + const dictionary = {}; + let lastChar = words[0][0]; + for (let index = 0; index < words.length; index += 1) { + const word = words[index]; + if (lastChar === word[0] && dictionary[word] === undefined) { + dictionary[word] = true; + lastChar = getLastChar(word); + continue; + } + return failUser(n, index + 1); + } + + return [0, 0]; +}; + +console.log( + solution(2, ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']) +); From e586fba7ddf0d3a4235e4284b8aa023c6ef64921 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Mon, 4 Jan 2021 19:01:59 +0900 Subject: [PATCH 171/193] =?UTF-8?q?=ED=81=90=20=ED=99=9C=EC=9A=A9=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20doublyLinkedList=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/doublyLinkedList.js | 108 ++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 src/grap3fruit/js/doublyLinkedList.js diff --git a/src/grap3fruit/js/doublyLinkedList.js b/src/grap3fruit/js/doublyLinkedList.js new file mode 100644 index 0000000..ead5907 --- /dev/null +++ b/src/grap3fruit/js/doublyLinkedList.js @@ -0,0 +1,108 @@ +class Node { + constructor(item) { + this.prev = null; + this.next = null; + this.item = item; + } +} + +class DoublyLinkedList { + constructor() { + this.head = new Node(null); + this.tail = new Node(null); + this.head.next = this.tail; + this.tail.prev = this.head; + this.length = 0; + } + + getLength() { + return this.length; + } + + push(item) { + const node = new Node(item); + this.length += 1; + + if (this.head.next === this.tail) { + node.prev = this.head; + node.next = this.tail; + this.head.next = node; + this.tail.prev = node; + return; + } + + let lastNode = this.tail.prev; + node.next = this.tail; + node.prev = lastNode; + lastNode.next = node; + this.tail.prev = node; + return; + } + + print() { + let current = this.head.next; + while (true) { + if (current === this.tail) { + return; + } + console.log(current.item); + current = current.next; + } + } + + pop() { + if (this.length === 0) { + return undefined; + } + this.length -= 1; + const popedNode = this.tail.prev; + popedNode.prev.next = this.tail; + this.tail.prev = popedNode.prev; + return popedNode.item; + } + + popLeft() { + if (this.length === 0) { + return undefined; + } + this.length -= 1; + const popedNode = this.head.next; + popedNode.next.prev = this.head; + this.head.next = popedNode.next; + return popedNode.item; + } + + filter(callback) { + let current = this.head.next; + const result = []; + while (current !== this.tail) { + console.log(current.item); + if (callback(current.item)) { + result.push(current.item); + } + current = current.next; + } + return result; + } +} + +const dl = new DoublyLinkedList(); + +dl.push([1, 0]); +dl.push([2, 1]); +dl.push([3, 1]); +dl.push([4, 2]); +dl.push([5, 2]); +console.log(dl.filter((el) => el[0] === 1 && el[1] === 0)); +console.log('---'); +console.log(dl.getLength()); +console.log('---'); +console.log(dl.popLeft()); +console.log('---'); +dl.print(); +console.log('---'); +console.log(dl.pop()); +console.log('---'); +console.log(dl.getLength()); +console.log('---'); +dl.print(); From 670e7ed1e46ea81bb9cad90abbc1239769552243 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Mon, 4 Jan 2021 19:02:30 +0900 Subject: [PATCH 172/193] =?UTF-8?q?=EA=B5=AC=EB=A6=84,=20boj=EC=97=90?= =?UTF-8?q?=EC=84=9C=20js=20=EC=9E=85=EB=A0=A5=20=EB=B0=9B=EB=8A=94=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/boj/input1_1.js | 16 ++++++++ src/grap3fruit/js/boj/input1_2.js | 19 +++++++++ src/grap3fruit/js/boj/test | 4 ++ src/grap3fruit/js/boj/test2 | 5 +++ src/grap3fruit/js/goorm/input1.js | 4 +- src/grap3fruit/js/goorm/input1.md | 0 src/grap3fruit/js/goorm/input1_1.js | 23 +++++++++++ src/grap3fruit/js/goorm/input1_2.js | 21 ++++++---- src/grap3fruit/js/goorm/input1_3.js | 47 ++++++++++++++++++++++ src/grap3fruit/js/goorm/input2.js | 4 +- src/grap3fruit/js/goorm/input2.md | 61 ----------------------------- src/grap3fruit/js/input.md | 1 + 12 files changed, 132 insertions(+), 73 deletions(-) create mode 100644 src/grap3fruit/js/boj/input1_1.js create mode 100644 src/grap3fruit/js/boj/input1_2.js create mode 100644 src/grap3fruit/js/boj/test create mode 100644 src/grap3fruit/js/boj/test2 delete mode 100644 src/grap3fruit/js/goorm/input1.md create mode 100644 src/grap3fruit/js/goorm/input1_1.js create mode 100644 src/grap3fruit/js/goorm/input1_3.js delete mode 100644 src/grap3fruit/js/goorm/input2.md create mode 100644 src/grap3fruit/js/input.md diff --git a/src/grap3fruit/js/boj/input1_1.js b/src/grap3fruit/js/boj/input1_1.js new file mode 100644 index 0000000..bdf20f4 --- /dev/null +++ b/src/grap3fruit/js/boj/input1_1.js @@ -0,0 +1,16 @@ +const solution = (N, data) => { + console.log(N); + console.log(data); +}; + +let fs = require('fs'); +let input = fs.readFileSync('test').toString().split('\n'); + +const N = +input[0]; +const data = []; +for (let i = 1; i < N + 1; i++) { + // 위에서 N을 받을떄 input[0]이 빠져나갔기 때문에 1~N을 받아야한다. + data.push(input[i].split(' ').map((el) => +el)); +} + +solution(N, data); diff --git a/src/grap3fruit/js/boj/input1_2.js b/src/grap3fruit/js/boj/input1_2.js new file mode 100644 index 0000000..cf99e7a --- /dev/null +++ b/src/grap3fruit/js/boj/input1_2.js @@ -0,0 +1,19 @@ +const solution = (N, info, data) => { + console.log(N); + const [X, Y] = info; + console.log(X, Y); + console.log(data); +}; + +let fs = require('fs'); +let input = fs.readFileSync('test2').toString().split('\n'); + +const N = +input[0]; +const info = input[1].split(' ').map((el) => +el); +const data = []; +for (let i = 2; i < N + 2; i++) { + // 위에서 N을 받을떄 input[0]이 빠져나갔기 때문에 1~N을 받아야한다. + data.push(input[i].split(' ').map((el) => +el)); +} + +solution(N, info, data); diff --git a/src/grap3fruit/js/boj/test b/src/grap3fruit/js/boj/test new file mode 100644 index 0000000..80de847 --- /dev/null +++ b/src/grap3fruit/js/boj/test @@ -0,0 +1,4 @@ +3 +1 2 3 +2 3 4 +3 4 5 \ No newline at end of file diff --git a/src/grap3fruit/js/boj/test2 b/src/grap3fruit/js/boj/test2 new file mode 100644 index 0000000..67313fa --- /dev/null +++ b/src/grap3fruit/js/boj/test2 @@ -0,0 +1,5 @@ +3 +2 3 +1 2 3 +2 3 4 +3 4 5 \ No newline at end of file diff --git a/src/grap3fruit/js/goorm/input1.js b/src/grap3fruit/js/goorm/input1.js index dc5cb8e..2acbab0 100644 --- a/src/grap3fruit/js/goorm/input1.js +++ b/src/grap3fruit/js/goorm/input1.js @@ -1,4 +1,4 @@ -const print = (N, data) => { +const solution = (N, data) => { console.log(N); console.log(data); }; @@ -28,6 +28,6 @@ rl.on('line', function (line) { rl.close(); } }).on('close', function () { - print(N, data); + solution(N, data); process.exit(); }); diff --git a/src/grap3fruit/js/goorm/input1.md b/src/grap3fruit/js/goorm/input1.md deleted file mode 100644 index e69de29..0000000 diff --git a/src/grap3fruit/js/goorm/input1_1.js b/src/grap3fruit/js/goorm/input1_1.js new file mode 100644 index 0000000..de07578 --- /dev/null +++ b/src/grap3fruit/js/goorm/input1_1.js @@ -0,0 +1,23 @@ +const solution = (data) => { + console.log(data); +}; + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let data = []; + +rl.on('line', function (line) { + data.push(line); + // data = line.split('').map((el) => el); + // data = line.split(' ').map((el) => el); + // data = line.split('').map((el) => +el); + + rl.close(); +}).on('close', function () { + solution(data); + process.exit(); +}); diff --git a/src/grap3fruit/js/goorm/input1_2.js b/src/grap3fruit/js/goorm/input1_2.js index 44c143c..ba0ba7e 100644 --- a/src/grap3fruit/js/goorm/input1_2.js +++ b/src/grap3fruit/js/goorm/input1_2.js @@ -1,6 +1,7 @@ const solution = (N, info, data) => { console.log(N); - console.log(info); + const [X, Y] = info; + console.log(X, Y); console.log(data); }; @@ -16,22 +17,26 @@ let count = 0; const data = []; rl.on('line', function (line) { - console.log(line); if (!N) { + // N이 null이면 N = +line; - } else if (N && !info) { + } else if (!info) { + // N이 null이 아닌데, info가 null이면 info = line.split(' ').map((el) => +el); } else { - data.push(line.split(' ').map((el) => +el)); + // N과 info가 null이 아니면 + data.push(line); // data.push(line.split('').map((el) => +el)); // data.push(line.split('').map((el) => el)); - // data.push(line); - count += 1; + // data.push(line.split(' ').map((el) => +el)); + count += 1; // data를 입력받으면 count를 증가시켜주고 } if (count === N) { + // count가 입력받아야하는 N일때 rl.close()를 호출해준다. rl.close(); } }).on('close', function () { - solution(N, info, data); - process.exit(); + // rl.close()를 호출하면 이 콜백함수로 들어오고 + solution(N, info, data); // solution을 실행 한 후 + process.exit(); // 프로세스를 종료한다. }); diff --git a/src/grap3fruit/js/goorm/input1_3.js b/src/grap3fruit/js/goorm/input1_3.js new file mode 100644 index 0000000..9784cef --- /dev/null +++ b/src/grap3fruit/js/goorm/input1_3.js @@ -0,0 +1,47 @@ +const solution = (N, data) => { + console.log(N); + console.log(data); +}; + +const readline = require('readline'); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +let T = null; +let N = null; +let info = null; +let countN = 0; +let countT = 0; +let data = []; + +rl.on('line', function (line) { + if (!T) { + T = +line; + } else if (!N) { + N = +line; + } else { + data.push(line); + // data.push(line.split('').map((el) => +el)); + // data.push(line.split('').map((el) => el)); + // data.push(line.split(' ').map((el) => +el)); + countN += 1; // data를 입력받으면 countN을 증가시켜주고 + } + if (countN === N) { + // N만큼 data를 잘 입력 받았으면 + solution(N, data); // solution을 호출하고 + N = null; // T, countT를 제외한 값들을 초기화해준다. + info = null; + countN = 0; + data = []; + + countT += 1; // 그리고 테스트 케이스 하나를 통과했으니 countT를 1 올려준다. + } + if (countT === T) { + // 입력받은 T 만큼 테스트 케이스를 통과하게되면 + rl.close(); // rl.close()를 호출하고 + } +}).on('close', function () { + process.exit(); // 종료한다. +}); diff --git a/src/grap3fruit/js/goorm/input2.js b/src/grap3fruit/js/goorm/input2.js index ecd6f81..e52121d 100644 --- a/src/grap3fruit/js/goorm/input2.js +++ b/src/grap3fruit/js/goorm/input2.js @@ -15,10 +15,10 @@ const readline = require('readline'); if (!N) { N = +line; } else { - // data.push(line); // 1 2 3 4 5 -> ['1 2 3 4 5'] + data.push(line); // 1 2 3 4 5 -> ['1 2 3 4 5'] // data.push(line.split(' ').map((el) => +el)); // 1 2 3 4 5 -> [1,2,3,4,5] // data.push(line.split('').map((el) => el)); // 12345 -> ['1','2','3','4','5'] - data.push(line.split('').map((el) => +el)); // 12345 -> [1,2,3,4,5] + // data.push(line.split('').map((el) => +el)); // 12345 -> [1,2,3,4,5] count += 1; } if (N === count) { diff --git a/src/grap3fruit/js/goorm/input2.md b/src/grap3fruit/js/goorm/input2.md deleted file mode 100644 index cb7eff6..0000000 --- a/src/grap3fruit/js/goorm/input2.md +++ /dev/null @@ -1,61 +0,0 @@ -test case - -``` -5 -12345 -23456 -34567 -45678 -56789 -``` - -결과 - -``` -5 -[ - [1,2,3,4,5], - [2,3,4,5,6], - [3,4,5,6,7], - [4,5,6,7,8], - [5,6,7,8,9] -] -``` - -```javascript -const print = (N, data) => { - console.log(N); - console.log(data); -}; - -const readline = require('readline'); - -(async () => { - let rl = readline.createInterface({ input: process.stdin }); - let N = null; - let count = 0; - const data = []; - - for await (const line of rl) { - if (!N) { - N = +line; - } else { - // data.push(line); // 1 2 3 4 5 -> ['1 2 3 4 5'] - // data.push(line.split(' ').map((el) => +el)); // 1 2 3 4 5 -> [1,2,3,4,5] - // data.push(line.split('').map((el) => el)); // 12345 -> ['1','2','3','4','5'] - data.push(line.split('').map((el) => +el)); // 12345 -> [1,2,3,4,5] - count += 1; - } - if (N === count) { - rl.close(); - } - } - - data.forEach((el) => { - console.log('len: ', el.length); - }); - - print(N, data); - process.exit(); -})(); -``` diff --git a/src/grap3fruit/js/input.md b/src/grap3fruit/js/input.md new file mode 100644 index 0000000..130cd01 --- /dev/null +++ b/src/grap3fruit/js/input.md @@ -0,0 +1 @@ +[구름(goorm), 백준(BOJ) 코딩 테스트 JavaScript로 입력받는 방법 정리](https://velog.io/@grap3fruit/%EA%B5%AC%EB%A6%84goorm-%EC%BD%94%ED%85%8C-javascript-%EB%A1%9C-%EC%9E%85%EB%A0%A5%EA%B0%92-%EB%B0%9B%EB%8A%94-%EB%B0%A9%EB%B2%95?fbclid=IwAR2HHZP8nb6pgOnBkFvDFmHJ3NCjj7bQBIogNjWRwBQ2sgDVu3l6LEZ94_4) 블로그 글 작성 From c9d588252b9fba07694c09efd9eebd7b7e1a211f Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Mon, 4 Jan 2021 19:09:14 +0900 Subject: [PATCH 173/193] =?UTF-8?q?[refactor]=20=EB=B8=94=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=20=EB=A7=81=ED=81=AC=20=EC=A3=BC=EC=86=8C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/input.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/grap3fruit/js/input.md b/src/grap3fruit/js/input.md index 130cd01..e9036a9 100644 --- a/src/grap3fruit/js/input.md +++ b/src/grap3fruit/js/input.md @@ -1 +1 @@ -[구름(goorm), 백준(BOJ) 코딩 테스트 JavaScript로 입력받는 방법 정리](https://velog.io/@grap3fruit/%EA%B5%AC%EB%A6%84goorm-%EC%BD%94%ED%85%8C-javascript-%EB%A1%9C-%EC%9E%85%EB%A0%A5%EA%B0%92-%EB%B0%9B%EB%8A%94-%EB%B0%A9%EB%B2%95?fbclid=IwAR2HHZP8nb6pgOnBkFvDFmHJ3NCjj7bQBIogNjWRwBQ2sgDVu3l6LEZ94_4) 블로그 글 작성 +[구름(goorm), 백준(BOJ) 코딩 테스트 JavaScript로 입력받는 방법 정리](https://velog.io/@grap3fruit/구름goorm-코테-javascript-로-입력값-받는-방법) 블로그 글 작성 From 70c6509269887771b56325b3eba8274218ef4e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Mon, 4 Jan 2021 21:46:47 +0900 Subject: [PATCH 174/193] =?UTF-8?q?add:=20queue=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/kyu9341/queue/queue.js | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/kyu9341/queue/queue.js diff --git a/src/kyu9341/queue/queue.js b/src/kyu9341/queue/queue.js new file mode 100644 index 0000000..1a0747e --- /dev/null +++ b/src/kyu9341/queue/queue.js @@ -0,0 +1,53 @@ +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class Queue { + constructor() { + this.head = null; + this.tail = null; + this.size = 0; + } + + push(data) { + const node = new Node(data); + if (this.isEmpty()) { + this.head = node; + this.head.next = this.tail; + } else this.tail.next = node; + + this.tail = node; + this.size += 1; + } + + pop() { + if (this.isEmpty()) return null; + if (this.head === this.tail) this.tail = null; + + const headData = this.head.data; + this.head = this.head.next; + this.size -= 1; + + return headData; + } + + isEmpty() { + return this.size === 0; + } + + getArray() { + const array = []; + if (this.isEmpty()) return array; + + let currentNode = this.head; + while (currentNode) { + array.push(currentNode.data); + currentNode = currentNode.next; + } + + return array; + } +} From ed57e46c70f81f2e2d9326203498439ff33e464a Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 5 Jan 2021 13:50:58 +0900 Subject: [PATCH 175/193] =?UTF-8?q?move=20:=20=ED=8C=8C=EC=9D=BC=20?= =?UTF-8?q?=EC=9C=84=EC=B9=98=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/{ => etc}/programmers_12981.js | 4 ---- 1 file changed, 4 deletions(-) rename src/do02reen24/{ => etc}/programmers_12981.js (87%) diff --git a/src/do02reen24/programmers_12981.js b/src/do02reen24/etc/programmers_12981.js similarity index 87% rename from src/do02reen24/programmers_12981.js rename to src/do02reen24/etc/programmers_12981.js index 2b31345..1411e33 100644 --- a/src/do02reen24/programmers_12981.js +++ b/src/do02reen24/etc/programmers_12981.js @@ -25,7 +25,3 @@ const solution = (n, words) => { return [0, 0]; }; - -console.log( - solution(2, ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']) -); From ab0554efbee4fd2691d89b68f185074db825b442 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 5 Jan 2021 14:18:52 +0900 Subject: [PATCH 176/193] =?UTF-8?q?solve=20:=20programmers=20=EB=84=A4?= =?UTF-8?q?=ED=8A=B8=EC=9B=8C=ED=81=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/do02reen24/BFS/programmers_43162.js | 23 +++++++++++++++++++++++ src/do02reen24/Review/week15.md | 5 +++++ 2 files changed, 28 insertions(+) create mode 100644 src/do02reen24/BFS/programmers_43162.js diff --git a/src/do02reen24/BFS/programmers_43162.js b/src/do02reen24/BFS/programmers_43162.js new file mode 100644 index 0000000..93110e2 --- /dev/null +++ b/src/do02reen24/BFS/programmers_43162.js @@ -0,0 +1,23 @@ +const solution = (n, computers) => { + let answer = 0; + const network = Array.from({ length: n }, () => 0); + + for (let i = 0; i < n; i += 1) { + if (network[i] !== 0) continue; + answer += 1; + network[i] = answer; + + const queue = [i]; + while (queue.length > 0) { + const visit = queue.pop(); + computers[visit].forEach((computer, index) => { + if (computer && network[index] === 0) { + queue.push(index); + network[index] = answer; + } + }); + } + } + + return answer; +}; diff --git a/src/do02reen24/Review/week15.md b/src/do02reen24/Review/week15.md index 0363baf..af356d6 100644 --- a/src/do02reen24/Review/week15.md +++ b/src/do02reen24/Review/week15.md @@ -9,3 +9,8 @@ ## :ballot_box_with_check: 프로그래머스 영어 끝말잇기(12981) - 각 경우를 고려하여 처리해주었다. + +## :ballot_box_with_check: 프로그래머스 네트워크(43162) + +- BFS의 개념을 활용하여 풀었다. +- 백준 2644번 문제와 비슷한 것 같다. From 5d7db95a13a24fa987a26996f6973c3cc32b1983 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 5 Jan 2021 14:44:40 +0900 Subject: [PATCH 177/193] =?UTF-8?q?remove=20:=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=EB=90=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=ED=8C=8C=EC=9D=BC=20?= =?UTF-8?q?=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contents/200905.md | 11 ----------- contents/README.md | 11 ----------- mom/mom20200905.md | 23 ----------------------- 3 files changed, 45 deletions(-) delete mode 100644 contents/200905.md delete mode 100644 contents/README.md delete mode 100644 mom/mom20200905.md diff --git a/contents/200905.md b/contents/200905.md deleted file mode 100644 index d29072b..0000000 --- a/contents/200905.md +++ /dev/null @@ -1,11 +0,0 @@ -# :fire: 금주의 문제 (200905) - -> 이번 주 주제는 자료구조입니다. - -https://www.acmicpc.net/problem/1158 - -https://www.acmicpc.net/problem/1406 - -https://www.acmicpc.net/problem/2346 - -https://www.acmicpc.net/problem/2957 \ No newline at end of file diff --git a/contents/README.md b/contents/README.md deleted file mode 100644 index 8d294c7..0000000 --- a/contents/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# :fire: 금주의 문제 (200912) - -> 이번 주 주제는 자료구조 2탄입니다. - -https://www.acmicpc.net/problem/11286 - -https://programmers.co.kr/learn/courses/30/lessons/42578 - -https://www.acmicpc.net/problem/1991 - -https://www.acmicpc.net/problem/2957 diff --git a/mom/mom20200905.md b/mom/mom20200905.md deleted file mode 100644 index ca4e8ee..0000000 --- a/mom/mom20200905.md +++ /dev/null @@ -1,23 +0,0 @@ -# :family_man_man_girl_boy: 회의록 - -### :question: 개인의 생활에 있어서 미션에 힘듦이 있었나. - -- 미션에 열중하느라 알고리즘에 대해 공부할 시간이 없긴 했으나 쉬운 3 문제, 어려운 1 문제 유지하는 것은 좋은 것 같다. - -- 향후 계속적인 조율의 시간을 가지는 것이 좋을 것 같다. - - - -### :hammer: 향후 피어 세션 계획 - -- **10:00 ~ 10:15** 스터디에 대한 이야기 - -- **10:15 ~ 11:50** 코드 분석 및 알고리즘 공유 - -- **11:50 ~ 12:00** 다음 주제 선정 및 문제 공유 - - - -### :bell: 기타 - -- 2957번 문제와 같은 경우 다음 주까지 다시 풀어오기 \ No newline at end of file From 0fee3913d7111e989bb9df8bb98fec61b4a79002 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 5 Jan 2021 17:20:40 +0900 Subject: [PATCH 178/193] chore : gitignore update --- src/do02reen24/.gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/do02reen24/.gitignore b/src/do02reen24/.gitignore index 24ab719..57d45e2 100644 --- a/src/do02reen24/.gitignore +++ b/src/do02reen24/.gitignore @@ -1,2 +1,2 @@ -카카오코테 +코딩테스트 .vscode \ No newline at end of file From 9b5433d251f9f0581bb96697c5bf345341bab317 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Tue, 5 Jan 2021 17:21:37 +0900 Subject: [PATCH 179/193] solve : codility 4 problems - binary gap - cyclic rotation - odd occurrences in array - stone wall --- .../codility/1_BinaryGap.js" | 16 +++++++++++++++ .../codility/2_CyclicRotation.js" | 9 +++++++++ .../codility/2_OddOccurrencesInArray.js" | 11 ++++++++++ .../codility/7_StoneWall.js" | 20 +++++++++++++++++++ .../codility/score.md" | 8 ++++++++ 5 files changed, 64 insertions(+) create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/1_BinaryGap.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_CyclicRotation.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_OddOccurrencesInArray.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/7_StoneWall.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/1_BinaryGap.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/1_BinaryGap.js" new file mode 100644 index 0000000..09f2236 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/1_BinaryGap.js" @@ -0,0 +1,16 @@ +const solution = (N) => { + let maxLength = 0; + const bin = N.toString(2).split(''); + + bin.reduce((length, word) => { + if (word === '1') { + if (maxLength < length) maxLength = length; + return 0; + } + return length + 1; + }, 0); + + return maxLength; +}; + +console.log(solution(32)); diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_CyclicRotation.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_CyclicRotation.js" new file mode 100644 index 0000000..d0580a2 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_CyclicRotation.js" @@ -0,0 +1,9 @@ +const solution = (A, K) => { + const length = A.length; + const k = K % length; + const front = A.slice(length - k, length); + const end = A.slice(0, length - k); + return front.concat(end); +}; + +console.log(solution([3, 8, 9, 7, 6], 3)); diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_OddOccurrencesInArray.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_OddOccurrencesInArray.js" new file mode 100644 index 0000000..873c722 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/2_OddOccurrencesInArray.js" @@ -0,0 +1,11 @@ +const solution = (A) => { + const count = A.reduce((arr, num) => { + if (arr[num] === undefined) arr[num] = 1; + else arr[num] += 1; + return arr; + }, {}); + for (const num in count) { + if (count[num] % 2 !== 0) return num; + } + return -1; +}; diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/7_StoneWall.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/7_StoneWall.js" new file mode 100644 index 0000000..67dd48d --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/7_StoneWall.js" @@ -0,0 +1,20 @@ +const solution = (H) => { + const queue = [H]; + let block = 0; + while (queue.length > 0) { + const h = queue.pop(); + if (h.length === 0) continue; + const min = Math.min.apply(null, h); + const remain = h.reduce((arr, cur) => { + if (cur === min) { + queue.push(arr); + return []; + } + arr.push(cur); + return arr; + }, []); + queue.push(remain); + block += 1; + } + return block; +}; diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" new file mode 100644 index 0000000..4716041 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" @@ -0,0 +1,8 @@ +# 📋 Codility 점수 기록 + +| Lesson | 문제 | 점수 | 비고 | +| :-----------------: | :-------------------: | :--: | :-------------------: | +| 1-Iterations | BinaryGap | 100 | - | +| 2-Arrays | CyclicRotation | 100 | - | +| 2-Arrays | OddOccurrencesInArray | 100 | - | +| 7-Stacks and Queues | StoneWall | 85 | 정확도 100%, 성능 77% | From d1c9fff17bfe696a6c60785f8dce75ed811a20a3 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Tue, 5 Jan 2021 21:46:01 +0900 Subject: [PATCH 180/193] =?UTF-8?q?15=EC=A3=BC=EC=B0=A8=20=EB=AC=B8?= =?UTF-8?q?=EC=A0=9C=ED=92=80=EC=9D=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/goorm/12981.js | 34 ++++++++++++++++++++ src/grap3fruit/js/goorm/42578.js | 26 +++++++++++++++ src/grap3fruit/js/goorm/43162.js | 54 ++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 src/grap3fruit/js/goorm/12981.js create mode 100644 src/grap3fruit/js/goorm/42578.js create mode 100644 src/grap3fruit/js/goorm/43162.js diff --git a/src/grap3fruit/js/goorm/12981.js b/src/grap3fruit/js/goorm/12981.js new file mode 100644 index 0000000..3a35eb8 --- /dev/null +++ b/src/grap3fruit/js/goorm/12981.js @@ -0,0 +1,34 @@ +const check = (words, n, word, idx, visited) => { + if (visited.includes(word)) { + return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; + } + if (idx > 0) { + if (words[idx - 1][words[idx - 1].length - 1] !== word[0]) { + return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; + } + } + return null; +}; + +function solution(n, words) { + let answer = null; + const visited = []; + + words.forEach((word, idx) => { + if (!answer) { + answer = check(words, n, word, idx, visited); + visited.push(word); + } + }); + if (!answer) { + answer = [0, 0]; + } + return answer; +} + +const n = 2; +const words = ['hello', 'two']; +// const words = ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']; +// const words = ['tank', 'kick', 'know', 'wheel', 'land', 'dream', 'mother', 'robot', 'tank']; + +solution(n, words); diff --git a/src/grap3fruit/js/goorm/42578.js b/src/grap3fruit/js/goorm/42578.js new file mode 100644 index 0000000..3ec1378 --- /dev/null +++ b/src/grap3fruit/js/goorm/42578.js @@ -0,0 +1,26 @@ +function solution(clothes) { + let answer = 1; + const data = {}; + + clothes.forEach((cloth) => { + if (!data[cloth[1]]) { + return (data[cloth[1]] = [cloth[0]]); + } + data[cloth[1]].push(cloth[0]); + }); + + for (const el in data) { + answer *= data[el].length + 1; + } + answer -= 1; + + return answer; +} + +const clothes = [ + ['yellow_hat', 'headgear'], + ['blue_sunglasses', 'eyewear'], + ['green_turban', 'headgear'], +]; + +console.log(solution(clothes)); diff --git a/src/grap3fruit/js/goorm/43162.js b/src/grap3fruit/js/goorm/43162.js new file mode 100644 index 0000000..bcd9b98 --- /dev/null +++ b/src/grap3fruit/js/goorm/43162.js @@ -0,0 +1,54 @@ +const bfs = (computers, root) => { + const visited = [root]; + let q = [computers[root]]; + + while (q.length > 0) { + let item = q.shift(); + + item.forEach((el, idx) => { + if (el === 1 && !visited.includes(idx)) { + q.push(computers[idx]); + visited.push(idx); + } + }); + } + + return visited; +}; + +function solution(n, computers) { + let answer = 0; + const visited = []; + + computers.forEach((_, idx) => { + let visitFlag = false; + visited.forEach((el) => { + if (el.includes(idx)) { + visitFlag = true; + } + }); + + if (!visitFlag) { + const newVisited = bfs(computers, idx); + visited.push(newVisited); + } + }); + + console.log(visited.length); + answer = visited.length; + return answer; +} + +const n = 3; +const computers = [ + [1, 1, 0], + [1, 1, 0], + [0, 0, 1], +]; +// const computers = [ +// [1, 1, 0], +// [1, 1, 1], +// [0, 1, 1], +// ]; + +solution(n, computers); From b83a89af6b2f0a44e1000b0aeb4851c592ac0a12 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Tue, 5 Jan 2021 21:49:28 +0900 Subject: [PATCH 181/193] =?UTF-8?q?=EC=9C=84=EC=9E=A5=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?map=EC=9C=BC=EB=A1=9C=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/goorm/42578_2.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/grap3fruit/js/goorm/42578_2.js diff --git a/src/grap3fruit/js/goorm/42578_2.js b/src/grap3fruit/js/goorm/42578_2.js new file mode 100644 index 0000000..f7b369c --- /dev/null +++ b/src/grap3fruit/js/goorm/42578_2.js @@ -0,0 +1,29 @@ +function solution(clothes) { + let answer = 1; + console.log(clothes); + + const map = new Map(); + + clothes.forEach((cloth) => { + if (!map.get(cloth[1])) { + return map.set(cloth[1], [cloth[0]]); + } + + map.get(cloth[1]).push(cloth[0]); + }); + + for (let key of map.keys()) { + answer *= map.get(key).length + 1; + } + answer -= 1; + + return answer; +} + +const clothes = [ + ['yellow_hat', 'headgear'], + ['blue_sunglasses', 'eyewear'], + ['green_turban', 'headgear'], +]; + +console.log(solution(clothes)); From 90776e17d789982eb0e58646e07c0f3533c7cf33 Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Wed, 6 Jan 2021 00:36:01 +0900 Subject: [PATCH 182/193] solve : codility lesson3 problems --- .../codility/3_FrogJmp.js" | 3 +++ .../codility/3_PermMissingElem.js" | 12 ++++++++++ .../codility/3_TapeEquilibrium.js" | 13 +++++++++++ .../codility/score.md" | 23 ++++++++++++++----- 4 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_FrogJmp.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_PermMissingElem.js" create mode 100644 "src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_FrogJmp.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_FrogJmp.js" new file mode 100644 index 0000000..dc00aa1 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_FrogJmp.js" @@ -0,0 +1,3 @@ +const solution = (X, Y, D) => { + return Math.ceil((Y - X) / D); +}; diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_PermMissingElem.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_PermMissingElem.js" new file mode 100644 index 0000000..9833357 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_PermMissingElem.js" @@ -0,0 +1,12 @@ +const solution = (A) => { + const N = A.length + 1; + const isNum = {}; + A.forEach((a) => { + isNum[a] = true; + }); + for (let n = 1; n < N + 1; n += 1) { + if (isNum[n] === true) continue; + return n; + } + return -1; +}; diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" new file mode 100644 index 0000000..8d5da62 --- /dev/null +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" @@ -0,0 +1,13 @@ +const solution = (A) => { + let answer; + let frontSum = 0; + let backSum = A.reduce((a, b) => a + b, 0); + for (let i = 0; i < A.length; i += 1) { + frontSum += A[i]; + backSum -= A[i]; + const absSub = Math.abs(frontSum - backSum); + if (absSub < answer || answer === undefined) answer = absSub; + } + + return answer; +}; diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" index 4716041..59475bf 100644 --- "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" @@ -1,8 +1,19 @@ # 📋 Codility 점수 기록 -| Lesson | 문제 | 점수 | 비고 | -| :-----------------: | :-------------------: | :--: | :-------------------: | -| 1-Iterations | BinaryGap | 100 | - | -| 2-Arrays | CyclicRotation | 100 | - | -| 2-Arrays | OddOccurrencesInArray | 100 | - | -| 7-Stacks and Queues | StoneWall | 85 | 정확도 100%, 성능 77% | +| Lesson | 문제 | 점수 | 비고 | 최종 제출 날짜 | +| :-----------------: | :-------------------: | :--: | :-------------------: | :------------: | +| 1-Iterations | BinaryGap | 100 | - | 2021-01-05 | +| 2-Arrays | CyclicRotation | 100 | - | 2021-01-05 | +| 2-Arrays | OddOccurrencesInArray | 100 | - | 2021-01-05 | +| 3-Time Complexity | FrogJmp | 100 | - | 2021-01-06 | +| 3-Time Complexity | PermMissingElem | 100 | - | 2021-01-06 | +| 3-Time Complexity | TapeEquilibrium | 84 | 정확도 71%, 성능 100% | 2021-01-06 | +| 7-Stacks and Queues | StoneWall | 85 | 정확도 100%, 성능 77% | 2021-01-05 | + +# 📚 Perfect Lesson + +> 모든 문제를 100%로 끝낸 Lesson + +* Lesson1 - Iterations + +* Lesson2 - Arrays \ No newline at end of file From 0dc189b003d55d98df6ae7d301f3b569ae551bcc Mon Sep 17 00:00:00 2001 From: do02reen24 Date: Wed, 6 Jan 2021 00:42:35 +0900 Subject: [PATCH 183/193] =?UTF-8?q?solve=20:=20tape=20equilibrium=20-=20?= =?UTF-8?q?=EA=B8=B0=EC=A1=B4=20=EB=A1=9C=EC=A7=81=EC=97=90=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=EA=B0=80=20=EC=9E=88=EC=9D=8C=EC=9D=84=20=EB=B0=9C?= =?UTF-8?q?=EA=B2=AC=ED=95=98=EA=B3=A0=20=EC=9D=B4=EB=A5=BC=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=ED=95=B4=EC=A3=BC=EC=97=88=EB=8B=A4.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../codility/3_TapeEquilibrium.js" | 2 +- .../codility/score.md" | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" index 8d5da62..3fc11e9 100644 --- "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/3_TapeEquilibrium.js" @@ -2,7 +2,7 @@ const solution = (A) => { let answer; let frontSum = 0; let backSum = A.reduce((a, b) => a + b, 0); - for (let i = 0; i < A.length; i += 1) { + for (let i = 0; i < A.length - 1; i += 1) { frontSum += A[i]; backSum -= A[i]; const absSub = Math.abs(frontSum - backSum); diff --git "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" index 59475bf..2debed9 100644 --- "a/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" +++ "b/src/do02reen24/\354\213\244\354\240\204\354\227\260\354\212\265/codility/score.md" @@ -7,7 +7,7 @@ | 2-Arrays | OddOccurrencesInArray | 100 | - | 2021-01-05 | | 3-Time Complexity | FrogJmp | 100 | - | 2021-01-06 | | 3-Time Complexity | PermMissingElem | 100 | - | 2021-01-06 | -| 3-Time Complexity | TapeEquilibrium | 84 | 정확도 71%, 성능 100% | 2021-01-06 | +| 3-Time Complexity | TapeEquilibrium | 100 | - | 2021-01-06 | | 7-Stacks and Queues | StoneWall | 85 | 정확도 100%, 성능 77% | 2021-01-05 | # 📚 Perfect Lesson @@ -16,4 +16,6 @@ * Lesson1 - Iterations -* Lesson2 - Arrays \ No newline at end of file +* Lesson2 - Arrays +* Lesson3 - Time Complexity + From 649fefb376b2615d7941b1a3001fa810c7626943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 6 Jan 2021 01:19:59 +0900 Subject: [PATCH 184/193] =?UTF-8?q?solve:=20programmers=20=EB=84=A4?= =?UTF-8?q?=ED=8A=B8=EC=9B=8C=ED=81=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 "src/kyu9341/programmers_\353\204\244\355\212\270\354\233\214\355\201\254/index.js" diff --git "a/src/kyu9341/programmers_\353\204\244\355\212\270\354\233\214\355\201\254/index.js" "b/src/kyu9341/programmers_\353\204\244\355\212\270\354\233\214\355\201\254/index.js" new file mode 100644 index 0000000..b095ce3 --- /dev/null +++ "b/src/kyu9341/programmers_\353\204\244\355\212\270\354\233\214\355\201\254/index.js" @@ -0,0 +1,50 @@ +const initArray = (size, val = null) => Array.from({ length: size }, () => val); +const initArrayInArray = size => + Array.from({ length: size }, () => new Array()); + +const solution = (n, computers) => { + const network = initArrayInArray(n); + const check = initArray(n, false); + + computers.forEach((row, rowIdx) => { + row.forEach((computer, colIdx) => { + if (rowIdx !== colIdx && computer) network[rowIdx].push(colIdx); + }); + }); + + const dfs = (node, network) => { + check[node] = true; + + network[node].forEach((_, computer) => { + const next = network[node][computer]; + if (!check[next]) dfs(next, network); + }); + }; + + const answer = network.reduce((acc, _, computer) => { + if (!check[computer]) { + dfs(computer, network); + return acc + 1; + } + return acc; + }, 0); + + return answer; +}; + +(() => { + const inputs = [ + [ + [1, 1, 0], + [1, 1, 0], + [0, 0, 1], + ], + [ + [1, 1, 0], + [1, 1, 1], + [0, 1, 1], + ], + ]; + + inputs.forEach(input => console.log(solution(input.length, input))); +})(); From 473584890b0524fa40bc3cd84ceb4aba0e7da526 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 6 Jan 2021 01:20:34 +0900 Subject: [PATCH 185/193] =?UTF-8?q?solve:=20programmers=20=EC=9C=84?= =?UTF-8?q?=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 "src/kyu9341/programmers_\354\234\204\354\236\245/index.js" diff --git "a/src/kyu9341/programmers_\354\234\204\354\236\245/index.js" "b/src/kyu9341/programmers_\354\234\204\354\236\245/index.js" new file mode 100644 index 0000000..c8a72df --- /dev/null +++ "b/src/kyu9341/programmers_\354\234\204\354\236\245/index.js" @@ -0,0 +1,23 @@ +const solution = clothes => { + const clothesMap = clothes.reduce((map, cur) => { + const countOfCurrentType = map.get(cur[1]); + + return map.set(cur[1], countOfCurrentType ? countOfCurrentType + 1 : 1); + }, new Map()); + + const count = + [...clothesMap.values()].reduce((acc, cur) => acc * (cur + 1), 1) - 1; + return count; +}; + +(() => { + const inputs = [ + [ + ['yellow_hat', 'headgear'], + ['blue_sunglasses', 'eyewear'], + ['green_turban', 'headgear'], + ], + ]; + + inputs.forEach(input => console.log(solution(input))); +})(); From 31950c5a8213a1bf602e28181a6ee01fca5ee211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=AF=E1=86=AB=E1=84=8B=E1=85=A7=E1=86=BC?= =?UTF-8?q?=E1=84=8B=E1=85=A5=E1=86=AB?= Date: Wed, 6 Jan 2021 01:21:23 +0900 Subject: [PATCH 186/193] =?UTF-8?q?solve:=20programmers=20=EC=98=81?= =?UTF-8?q?=EC=96=B4=EB=81=9D=EB=A7=90=EC=9E=87=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../index.js" | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 "src/kyu9341/programmers_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/index.js" diff --git "a/src/kyu9341/programmers_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/index.js" "b/src/kyu9341/programmers_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/index.js" new file mode 100644 index 0000000..b44f5f0 --- /dev/null +++ "b/src/kyu9341/programmers_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/index.js" @@ -0,0 +1,63 @@ +const solution = (n, words) => { + const set = new Set(); + let prevWrod = ''; + + for (const [idx, word] of words.entries()) { + const beNotEqual = + idx && prevWrod.charAt(prevWrod.length - 1) !== word.charAt(0); + + if (set.has(word) || beNotEqual) { + const num = (idx + 1) % n || n; + const count = Math.floor((idx + 1) / n) + Number(num !== n); + + return [num, count]; + } + + set.add(word); + prevWrod = word; + } + + return [0, 0]; +}; + +(() => { + const inputs = [ + { + n: 3, + words: [ + 'tank', + 'kick', + 'know', + 'wheel', + 'land', + 'dream', + 'mother', + 'robot', + 'tank', + ], + }, + { + n: 5, + words: [ + 'hello', + 'observe', + 'effect', + 'take', + 'either', + 'recognize', + 'encourage', + 'ensure', + 'establish', + 'hang', + 'gather', + 'refer', + 'reference', + 'estimate', + 'executive', + ], + }, + { n: 2, words: ['hello', 'one', 'even', 'never', 'now', 'world', 'draw'] }, + ]; + + inputs.forEach(input => console.log(solution(input.n, input.words))); +})(); From dc58fe572e5083e0e7e70ebc895832683953df33 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 6 Jan 2021 18:52:23 +0900 Subject: [PATCH 187/193] =?UTF-8?q?solve:=20programmers=20=EC=9C=84?= =?UTF-8?q?=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 조합을 통한 풀이 --- .../pgs_\354\234\204\354\236\245.js" | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 "src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.js" diff --git "a/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.js" "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.js" new file mode 100644 index 0000000..c8b00b6 --- /dev/null +++ "b/src/Do-ho/dataStructor/pgs_\354\234\204\354\236\245/pgs_\354\234\204\354\236\245.js" @@ -0,0 +1,8 @@ +const solution = clothes => { + const clothesObject = clothes.reduce((acc, [name, kind]) => { + acc.hasOwnProperty(kind)? acc[kind] += 1 : acc[kind] = 1; + return acc; + }, new Object()); + + return Object.values(clothesObject).reduce((acc, val) => acc *= val + 1, 1) - 1; +} \ No newline at end of file From 4dda60932d233a1f84571b9dfda2670b155f1566 Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 6 Jan 2021 18:52:37 +0900 Subject: [PATCH 188/193] =?UTF-8?q?solve:=20programmers=20=EB=84=A4?= =?UTF-8?q?=ED=8A=B8=EC=9B=8C=ED=81=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dfs를 통한 풀이 --- ...44\355\212\270\354\233\214\355\201\254.js" | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 "src/Do-ho/dfsbfs/pgs_\353\204\244\355\212\270\354\233\214\355\201\254/pgs_\353\204\244\355\212\270\354\233\214\355\201\254.js" diff --git "a/src/Do-ho/dfsbfs/pgs_\353\204\244\355\212\270\354\233\214\355\201\254/pgs_\353\204\244\355\212\270\354\233\214\355\201\254.js" "b/src/Do-ho/dfsbfs/pgs_\353\204\244\355\212\270\354\233\214\355\201\254/pgs_\353\204\244\355\212\270\354\233\214\355\201\254.js" new file mode 100644 index 0000000..9a04453 --- /dev/null +++ "b/src/Do-ho/dfsbfs/pgs_\353\204\244\355\212\270\354\233\214\355\201\254/pgs_\353\204\244\355\212\270\354\233\214\355\201\254.js" @@ -0,0 +1,26 @@ +const solution = (n, computers) => { + let answer = 0; + let visited = new Array(n).fill(false); + let queue = []; + const loopArray = [... new Array(n).keys()]; + const isEmpty = () => queue.length !== 0; + + const dfs = () => { + const targetIdx = queue.pop(); + const target = computers[targetIdx] + loopArray.forEach((idx) => { + if(visited[idx] || target[idx] === 0) return; + queue.push(idx); + visited[idx] = true; + }); + } + + loopArray.forEach((computerID) => { + if(visited[computerID]) return; + queue.push(computerID); + while(isEmpty()) dfs(); + answer++; + }) + + return answer; +} \ No newline at end of file From 448f895d96b9d3af41583d15d0a5ccc3c6ee048d Mon Sep 17 00:00:00 2001 From: Do-ho Date: Wed, 6 Jan 2021 18:52:48 +0900 Subject: [PATCH 189/193] =?UTF-8?q?solve:=20programmers=20=EC=98=81?= =?UTF-8?q?=EC=96=B4=EB=81=9D=EB=A7=90=EC=9E=87=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 단순 구현 문제 --- ...35\353\247\220\354\236\207\352\270\260.js" | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 "src/Do-ho/implementation/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260.js" diff --git "a/src/Do-ho/implementation/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260.js" "b/src/Do-ho/implementation/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260.js" new file mode 100644 index 0000000..3383aab --- /dev/null +++ "b/src/Do-ho/implementation/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260/pgs_\354\230\201\354\226\264\353\201\235\353\247\220\354\236\207\352\270\260.js" @@ -0,0 +1,21 @@ +const solution = (n, words) => { + let [people, order] = [0, 0]; + let prevText = null; + let wordSet = []; + const isNotPrevTextNull = () => prevText !== null; + const isNotMatchWord = (word) => prevText[prevText.length - 1] !== word[0]; + const isContainWordSet = (word) => wordSet.includes(word); + + for (let i=0; i Date: Wed, 6 Jan 2021 18:55:33 +0900 Subject: [PATCH 190/193] =?UTF-8?q?docs:=20PR=20Template=20=EC=97=85?= =?UTF-8?q?=EB=A1=9C=EB=93=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/PULL_REQUEST_TEMPLATE.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..722558e --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,8 @@ +## 📚 문제 +- 문제 1 +- 문제 2 +- 문제 3 +- 문제 4 + +## 📋 하고 싶은 말 +- 하고 싶은 말 1 \ No newline at end of file From 144e43fd5ed088df53e9f7d64dcfcbd9228b0961 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Wed, 6 Jan 2021 20:39:33 +0900 Subject: [PATCH 191/193] =?UTF-8?q?15=ED=9A=8C=EC=B0=A8=20readme=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/programmers/12981.js | 34 +++++++++++++++ src/grap3fruit/js/programmers/12981.md | 11 +++++ src/grap3fruit/js/programmers/42578.js | 26 ++++++++++++ src/grap3fruit/js/programmers/42578.md | 9 ++++ src/grap3fruit/js/programmers/42578_2.js | 29 +++++++++++++ src/grap3fruit/js/programmers/43162.js | 54 ++++++++++++++++++++++++ src/grap3fruit/js/programmers/43162.md | 11 +++++ 7 files changed, 174 insertions(+) create mode 100644 src/grap3fruit/js/programmers/12981.js create mode 100644 src/grap3fruit/js/programmers/12981.md create mode 100644 src/grap3fruit/js/programmers/42578.js create mode 100644 src/grap3fruit/js/programmers/42578.md create mode 100644 src/grap3fruit/js/programmers/42578_2.js create mode 100644 src/grap3fruit/js/programmers/43162.js create mode 100644 src/grap3fruit/js/programmers/43162.md diff --git a/src/grap3fruit/js/programmers/12981.js b/src/grap3fruit/js/programmers/12981.js new file mode 100644 index 0000000..3a35eb8 --- /dev/null +++ b/src/grap3fruit/js/programmers/12981.js @@ -0,0 +1,34 @@ +const check = (words, n, word, idx, visited) => { + if (visited.includes(word)) { + return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; + } + if (idx > 0) { + if (words[idx - 1][words[idx - 1].length - 1] !== word[0]) { + return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; + } + } + return null; +}; + +function solution(n, words) { + let answer = null; + const visited = []; + + words.forEach((word, idx) => { + if (!answer) { + answer = check(words, n, word, idx, visited); + visited.push(word); + } + }); + if (!answer) { + answer = [0, 0]; + } + return answer; +} + +const n = 2; +const words = ['hello', 'two']; +// const words = ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']; +// const words = ['tank', 'kick', 'know', 'wheel', 'land', 'dream', 'mother', 'robot', 'tank']; + +solution(n, words); diff --git a/src/grap3fruit/js/programmers/12981.md b/src/grap3fruit/js/programmers/12981.md new file mode 100644 index 0000000..a7d413a --- /dev/null +++ b/src/grap3fruit/js/programmers/12981.md @@ -0,0 +1,11 @@ +# 12981 영어 끝말잇기 - 성공 + +## 아이디어 구현 + +단순 구현 문제 + +words를 돌면서 조건에 맞는것 리턴 해주면 됨. + +[번호, 차례]를 잘 출력하는게 까다로웠음. + +차례는 항상 올림으로 해주면 맞게 된다. diff --git a/src/grap3fruit/js/programmers/42578.js b/src/grap3fruit/js/programmers/42578.js new file mode 100644 index 0000000..3ec1378 --- /dev/null +++ b/src/grap3fruit/js/programmers/42578.js @@ -0,0 +1,26 @@ +function solution(clothes) { + let answer = 1; + const data = {}; + + clothes.forEach((cloth) => { + if (!data[cloth[1]]) { + return (data[cloth[1]] = [cloth[0]]); + } + data[cloth[1]].push(cloth[0]); + }); + + for (const el in data) { + answer *= data[el].length + 1; + } + answer -= 1; + + return answer; +} + +const clothes = [ + ['yellow_hat', 'headgear'], + ['blue_sunglasses', 'eyewear'], + ['green_turban', 'headgear'], +]; + +console.log(solution(clothes)); diff --git a/src/grap3fruit/js/programmers/42578.md b/src/grap3fruit/js/programmers/42578.md new file mode 100644 index 0000000..18702d0 --- /dev/null +++ b/src/grap3fruit/js/programmers/42578.md @@ -0,0 +1,9 @@ +# 42578 위장 - 성공 + +## 아이디어 구현 + +이 문제가 왜 해시인가? 딕셔너리 아닌가? 했더니 + +해시맵 === 딕셔너리 네요. 같은 자료구조인데 여러가지로 불리는. + +[키기반의 컬렉션](https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Keyed_collections#Maps) 참고해서, map 써서도 구현해봤습니다 diff --git a/src/grap3fruit/js/programmers/42578_2.js b/src/grap3fruit/js/programmers/42578_2.js new file mode 100644 index 0000000..f7b369c --- /dev/null +++ b/src/grap3fruit/js/programmers/42578_2.js @@ -0,0 +1,29 @@ +function solution(clothes) { + let answer = 1; + console.log(clothes); + + const map = new Map(); + + clothes.forEach((cloth) => { + if (!map.get(cloth[1])) { + return map.set(cloth[1], [cloth[0]]); + } + + map.get(cloth[1]).push(cloth[0]); + }); + + for (let key of map.keys()) { + answer *= map.get(key).length + 1; + } + answer -= 1; + + return answer; +} + +const clothes = [ + ['yellow_hat', 'headgear'], + ['blue_sunglasses', 'eyewear'], + ['green_turban', 'headgear'], +]; + +console.log(solution(clothes)); diff --git a/src/grap3fruit/js/programmers/43162.js b/src/grap3fruit/js/programmers/43162.js new file mode 100644 index 0000000..bcd9b98 --- /dev/null +++ b/src/grap3fruit/js/programmers/43162.js @@ -0,0 +1,54 @@ +const bfs = (computers, root) => { + const visited = [root]; + let q = [computers[root]]; + + while (q.length > 0) { + let item = q.shift(); + + item.forEach((el, idx) => { + if (el === 1 && !visited.includes(idx)) { + q.push(computers[idx]); + visited.push(idx); + } + }); + } + + return visited; +}; + +function solution(n, computers) { + let answer = 0; + const visited = []; + + computers.forEach((_, idx) => { + let visitFlag = false; + visited.forEach((el) => { + if (el.includes(idx)) { + visitFlag = true; + } + }); + + if (!visitFlag) { + const newVisited = bfs(computers, idx); + visited.push(newVisited); + } + }); + + console.log(visited.length); + answer = visited.length; + return answer; +} + +const n = 3; +const computers = [ + [1, 1, 0], + [1, 1, 0], + [0, 0, 1], +]; +// const computers = [ +// [1, 1, 0], +// [1, 1, 1], +// [0, 1, 1], +// ]; + +solution(n, computers); diff --git a/src/grap3fruit/js/programmers/43162.md b/src/grap3fruit/js/programmers/43162.md new file mode 100644 index 0000000..107a9be --- /dev/null +++ b/src/grap3fruit/js/programmers/43162.md @@ -0,0 +1,11 @@ +# 43162 네트워크 - 성공 + +## BFS + +bfs에서 최단거리를 구할 필요는 없고, 지나간 모든 경로를 visited에 담아서 반환하면 이걸 하나의 네트워크라고 생각한다. + +각각의 컴퓨터가 root일때 네트워크를 구하고 겹치지 않는 네트워크의 개수를 구해주면 된다. + +겹치지 않도록 하기위해 bfs로 root를 넣기 전, network를 모두 체크해서 겹치는 root가 있으면 같은 네트워크가 이미 있다는 것이므로 pass 했다. + +위 조건에 따른 모든 network를 구한 후 개수를 세면 끝. From e00c6912882488de8787aa3fbcf91295161a2fae Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Wed, 6 Jan 2021 20:40:12 +0900 Subject: [PATCH 192/193] =?UTF-8?q?=ED=8C=8C=EC=9D=BC=20=EC=9E=98=EB=AA=BB?= =?UTF-8?q?=20=EB=84=A3=EC=9D=80=EA=B2=83=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/goorm/12981.js | 34 ------------------- src/grap3fruit/js/goorm/42578.js | 26 -------------- src/grap3fruit/js/goorm/42578_2.js | 29 ---------------- src/grap3fruit/js/goorm/43162.js | 54 ------------------------------ 4 files changed, 143 deletions(-) delete mode 100644 src/grap3fruit/js/goorm/12981.js delete mode 100644 src/grap3fruit/js/goorm/42578.js delete mode 100644 src/grap3fruit/js/goorm/42578_2.js delete mode 100644 src/grap3fruit/js/goorm/43162.js diff --git a/src/grap3fruit/js/goorm/12981.js b/src/grap3fruit/js/goorm/12981.js deleted file mode 100644 index 3a35eb8..0000000 --- a/src/grap3fruit/js/goorm/12981.js +++ /dev/null @@ -1,34 +0,0 @@ -const check = (words, n, word, idx, visited) => { - if (visited.includes(word)) { - return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; - } - if (idx > 0) { - if (words[idx - 1][words[idx - 1].length - 1] !== word[0]) { - return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; - } - } - return null; -}; - -function solution(n, words) { - let answer = null; - const visited = []; - - words.forEach((word, idx) => { - if (!answer) { - answer = check(words, n, word, idx, visited); - visited.push(word); - } - }); - if (!answer) { - answer = [0, 0]; - } - return answer; -} - -const n = 2; -const words = ['hello', 'two']; -// const words = ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']; -// const words = ['tank', 'kick', 'know', 'wheel', 'land', 'dream', 'mother', 'robot', 'tank']; - -solution(n, words); diff --git a/src/grap3fruit/js/goorm/42578.js b/src/grap3fruit/js/goorm/42578.js deleted file mode 100644 index 3ec1378..0000000 --- a/src/grap3fruit/js/goorm/42578.js +++ /dev/null @@ -1,26 +0,0 @@ -function solution(clothes) { - let answer = 1; - const data = {}; - - clothes.forEach((cloth) => { - if (!data[cloth[1]]) { - return (data[cloth[1]] = [cloth[0]]); - } - data[cloth[1]].push(cloth[0]); - }); - - for (const el in data) { - answer *= data[el].length + 1; - } - answer -= 1; - - return answer; -} - -const clothes = [ - ['yellow_hat', 'headgear'], - ['blue_sunglasses', 'eyewear'], - ['green_turban', 'headgear'], -]; - -console.log(solution(clothes)); diff --git a/src/grap3fruit/js/goorm/42578_2.js b/src/grap3fruit/js/goorm/42578_2.js deleted file mode 100644 index f7b369c..0000000 --- a/src/grap3fruit/js/goorm/42578_2.js +++ /dev/null @@ -1,29 +0,0 @@ -function solution(clothes) { - let answer = 1; - console.log(clothes); - - const map = new Map(); - - clothes.forEach((cloth) => { - if (!map.get(cloth[1])) { - return map.set(cloth[1], [cloth[0]]); - } - - map.get(cloth[1]).push(cloth[0]); - }); - - for (let key of map.keys()) { - answer *= map.get(key).length + 1; - } - answer -= 1; - - return answer; -} - -const clothes = [ - ['yellow_hat', 'headgear'], - ['blue_sunglasses', 'eyewear'], - ['green_turban', 'headgear'], -]; - -console.log(solution(clothes)); diff --git a/src/grap3fruit/js/goorm/43162.js b/src/grap3fruit/js/goorm/43162.js deleted file mode 100644 index bcd9b98..0000000 --- a/src/grap3fruit/js/goorm/43162.js +++ /dev/null @@ -1,54 +0,0 @@ -const bfs = (computers, root) => { - const visited = [root]; - let q = [computers[root]]; - - while (q.length > 0) { - let item = q.shift(); - - item.forEach((el, idx) => { - if (el === 1 && !visited.includes(idx)) { - q.push(computers[idx]); - visited.push(idx); - } - }); - } - - return visited; -}; - -function solution(n, computers) { - let answer = 0; - const visited = []; - - computers.forEach((_, idx) => { - let visitFlag = false; - visited.forEach((el) => { - if (el.includes(idx)) { - visitFlag = true; - } - }); - - if (!visitFlag) { - const newVisited = bfs(computers, idx); - visited.push(newVisited); - } - }); - - console.log(visited.length); - answer = visited.length; - return answer; -} - -const n = 3; -const computers = [ - [1, 1, 0], - [1, 1, 0], - [0, 0, 1], -]; -// const computers = [ -// [1, 1, 0], -// [1, 1, 1], -// [0, 1, 1], -// ]; - -solution(n, computers); From f13aa2c33a839e5fd01bdcce1cf684e8e54dc0e0 Mon Sep 17 00:00:00 2001 From: grap3fruit Date: Wed, 6 Jan 2021 21:49:34 +0900 Subject: [PATCH 193/193] =?UTF-8?q?15=EC=A3=BC=EC=B0=A8=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=EB=A6=AC=EB=B7=B0=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/grap3fruit/js/programmers/12981.js | 22 +++++++++++++--------- src/grap3fruit/js/programmers/43162.js | 7 +------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/grap3fruit/js/programmers/12981.js b/src/grap3fruit/js/programmers/12981.js index 3a35eb8..57214da 100644 --- a/src/grap3fruit/js/programmers/12981.js +++ b/src/grap3fruit/js/programmers/12981.js @@ -1,10 +1,14 @@ -const check = (words, n, word, idx, visited) => { - if (visited.includes(word)) { - return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; +const getResult = (idx, n) => { + return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; +}; + +const check = (lastWord, n, word, idx, visited) => { + if (visited.get(word)) { + return getResult(idx, n); } if (idx > 0) { - if (words[idx - 1][words[idx - 1].length - 1] !== word[0]) { - return [(idx % n) + 1, Math.ceil((idx + 1) / n)]; + if (lastWord[lastWord.length - 1] !== word[0]) { + return getResult(idx, n); } } return null; @@ -12,12 +16,12 @@ const check = (words, n, word, idx, visited) => { function solution(n, words) { let answer = null; - const visited = []; + const visited = new Map(); words.forEach((word, idx) => { if (!answer) { - answer = check(words, n, word, idx, visited); - visited.push(word); + answer = check(words[idx - 1], n, word, idx, visited); + visited.set(word, true); } }); if (!answer) { @@ -31,4 +35,4 @@ const words = ['hello', 'two']; // const words = ['hello', 'one', 'even', 'never', 'now', 'world', 'draw']; // const words = ['tank', 'kick', 'know', 'wheel', 'land', 'dream', 'mother', 'robot', 'tank']; -solution(n, words); +console.log(solution(n, words)); diff --git a/src/grap3fruit/js/programmers/43162.js b/src/grap3fruit/js/programmers/43162.js index bcd9b98..0affc25 100644 --- a/src/grap3fruit/js/programmers/43162.js +++ b/src/grap3fruit/js/programmers/43162.js @@ -21,12 +21,7 @@ function solution(n, computers) { const visited = []; computers.forEach((_, idx) => { - let visitFlag = false; - visited.forEach((el) => { - if (el.includes(idx)) { - visitFlag = true; - } - }); + const visitFlag = visited.some((el) => el.includes(idx)); if (!visitFlag) { const newVisited = bfs(computers, idx);