diff --git "a/src/\352\260\225\353\217\231\354\204\235/week14/Programmers_60061.java" "b/src/\352\260\225\353\217\231\354\204\235/week14/Programmers_60061.java" new file mode 100644 index 0000000..3ea7136 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week14/Programmers_60061.java" @@ -0,0 +1,83 @@ +package programmers; + +import java.util.ArrayList; + +// 기둥과 보 설치 +/* + * 기둥과 보를 설치할 때는 문제의 조건에 맞게 메소드를 분리하여 진행. + * 삭제할 때는 일단 삭제한 후 연결된 부분들이 전부 건축가능한 상태면 그대로 삭제 진행, 하나라도 건축불가능하면 삭제한거 다시 취소 + * 인덱스 범위 고려시 입력값에서 기둥은 y==N인 경우가 없고, 보는 x==N인 경우가 없음! + * 복붙 했다가 오타 못찾아서 디버깅하는데 시간을 너무 소비했다.... + * 항상 복붙할때는 조심하자! + */ +public class Programmers_60061 { + + public static void main(String[] args) { + int n = 5; + int[][] build_frame = {{1,0,0,1},{1,1,1,1},{2,1,0,1},{2,2,1,1},{5,0,0,1},{5,1,0,1},{4,2,1,1},{3,2,1,1}}; + System.out.println(solution(n, build_frame)); + } + + static boolean[][][] map; + static int N; + public static ArrayList solution(int n, int[][] build_frame) { + N = n; + map = new boolean[n+1][n+1][2]; // [x][y][0또는1] 0은 기둥, 1은 보 + for(int i=0,len=build_frame.length; i list = new ArrayList(); + for(int i=0; i0 && map[x-1][y][1])); // 바로 아래 기둥이 있거나 양쪽 중 하나라도 보가 있으면 + }else { // 바닥이면 무조건 설치 + return true; + } + } + + public static boolean buildBoPossible(int x, int y) { // map[x][y]에 보 설치가능 여부 + return map[x][y-1][0] || map[x+1][y-1][0] || (x>0 && map[x-1][y][1] && map[x+1][y][1]); // 양 쪽 중 하나라도 아래 기둥이 있거나, 양 옆으로 보가 있으면 + } + + public static boolean removeGidoongPossible(int x, int y) { // map[x][y]에 기둥 삭제가능 여부 + boolean flag = true; + if(map[x][y+1][0] && !buildGidoongPossible(x, y+1)) flag=false; // 바로 위에 기둥이 존재하지만 기둥을 지을 수 없으면 false + if(x>0 && map[x-1][y+1][1] && !buildBoPossible(x-1, y+1)) flag=false; // 바로 왼쪽에 보가 존재하지만 보를 지을 수 없으면 false + if(map[x][y+1][1] && !buildBoPossible(x, y+1)) flag=false; // 바로 오른쪽에 보가 존재하지만 보를 지을 수 없으면 false + return flag; + } + + public static boolean removeBoPossible(int x, int y) { // map[x][y]에 보 삭제가능 여부 + boolean flag = true; + if(map[x][y][0] && !buildGidoongPossible(x, y)) flag=false; // 해당 위치에 기둥이 존재하지만 기둥을 지을 수 없으면 false + if(map[x+1][y][0] && !buildGidoongPossible(x+1, y)) flag=false; // 해당 위치 오른쪽에 기둥이 존재하지만 기둥을 지을 수 없으면 false + if(x>0 && map[x-1][y][1] && !buildBoPossible(x-1, y)) flag=false; // 바로 왼쪽에 보가 존재하지만 보를 지을 수 없으면 false + if(map[x+1][y][1] && !buildBoPossible(x+1, y)) flag=false; // 바로 오른쪽에 보가 존재하지만 보를 지을 수 없으면 false + return flag; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week17/Baekjoon_10282.java" "b/src/\352\260\225\353\217\231\354\204\235/week17/Baekjoon_10282.java" new file mode 100644 index 0000000..40027ac --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week17/Baekjoon_10282.java" @@ -0,0 +1,91 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.PriorityQueue; + +// 해킹 +/* + * 전형적인 다익스트라 알고리즘을 이용하는 문제이다. + * 처음에 인접행렬을 이용하여 풀었더니 메모리가 초과되었다. (정점은 많지만 간선의 갯수가 적을 때 불리) + * 그래서 인접리스트를 이용하여 해결하였다. + * 오랜만에 다익스트라를 접해서 그런지 많이 까먹었다. 다시 연습할 필요가 있는 것 같다. + * 시간복잡도: O(N): NlonN (PQ의 힙정렬) + */ +public class Baekjoon_10282 { + + static class Vertex implements Comparable { + int no, distance; + + public Vertex(int no, int distance) { + super(); + this.no = no; + this.distance = distance; + } + + @Override + public int compareTo(Vertex o) { + return Integer.compare(this.distance, o.distance); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + final int INFINITY = Integer.MAX_VALUE; + int T = Integer.parseInt(br.readLine()); + for(int tc=0; tc[] adjList = new ArrayList[n]; // 인접리스트 + for(int i=0; i(); + } + int[] distance = new int[n]; + boolean[] visited = new boolean[n]; + + for(int i=0; i pq = new PriorityQueue(); + pq.offer(new Vertex(c, distance[c])); + + Vertex current = null; + + while (!pq.isEmpty()) { + current = pq.poll(); // 방문하지 않은 정점들 중 최소가중치의 정점 선택 + if (visited[current.no]) continue; // 이미 방문한 정점이면 pass + + visited[current.no] = true; // 선택 정점 방문 처리 + + for (int i = 0; i < adjList[current.no].size(); ++i) { // current정점을 경유지로 하여 갈수 있는 다른 방문하지 않은 정점들에 대한 처리 + Vertex nextV = adjList[current.no].get(i); // 목적 정점 + if (!visited[nextV.no] && distance[nextV.no] > current.distance + nextV.distance) { // 기존의 최적화된 값보다 현재정점을 경유해서 목표 정점에 닿는 거리가 짧으면 + distance[nextV.no] = current.distance + nextV.distance; // 값 최적화 + pq.offer(new Vertex(nextV.no, distance[nextV.no])); // 큐에 넣기 + } + } + } + int resultNum=0,resultTime=0; + for(int i=0,len=distance.length; i0) { // 양수만 있으면 + answer[0] = arr[0]; // 처음 두 수를 저장 + answer[1] = arr[1]; + }else { // 음수와 양수가 같이 있으면 + int negativeIdx = -1; // 음수를 가리킬 인덱스 + int positiveIdx = -1; // 양수를 가리킬 인덱스 + + for(int i=0; i0) { // 연속한 두 수가 음수와 양수이면 + negativeIdx=i; positiveIdx=i+1; // 음수와 양수의 인덱스를 저장 + break; + } + } + + // 최대 음수 2개만 선택 + if(negativeIdx>0) { + answer[0] = arr[negativeIdx-1]; + answer[1] = arr[negativeIdx]; + } + // 최소 양수 2개만 선택 + if(positiveIdxarr[positiveIdx]+arr[positiveIdx+1]) { // 음수가 1개밖에 없거나 양수 2개 합의 절댓값이 더 작을 경우 + answer[0] = arr[positiveIdx]; + answer[1] = arr[positiveIdx+1]; + } + } + // 각각 1개씩 선택 + if(answer[0]==0 || Math.abs(answer[0]+answer[1])>arr[negativeIdx]+arr[positiveIdx]) { // 음수와 양수가 1개씩 밖에 없거나 양수와 음수 하나씩 합의 절댓값이 더 작을 경우 + answer[0] = arr[negativeIdx]; + answer[1] = arr[positiveIdx]; + } + while(true) { + if(negativeIdx==0 && positiveIdx==N-1) break; // 양쪽 포인터가 모두 끝을 가리키면 종료 + if(negativeIdx==0) { // 더 이상의 음수가 없으면 + positiveIdx++; // 양수를 한 칸 이동 + }else if(positiveIdx==N-1) { // 더 이상의 양수가 없으면 + negativeIdx--; // 음수를 한 칸 이동 + }else { // 둘 다 아직 숫자들이 남아 있으면 + int nextN = negativeIdx-1; // 다음 음수 + int nextP = positiveIdx+1; // 다음 양수 + if(Math.abs(arr[nextN]) removedStack = new Stack(); // 삭제된 행들의 인덱스를 저장하는 스택 + int totalSize = n; // 초기 행 전체 갯수 + for(int i=0,length=cmd.length; i[] adjList = new LinkedList[N+1]; // {건물번호, 해당건물까지 걸리는 누적 시간}을 저장하는 인접행렬 + for(int i=1; i(); + } + + line = br.readLine().split(" "); + for(int i=1; i q = new LinkedList(); + for(int i=1; i{ + int no,distance; + public Vertex(int no, int distance) { + super(); + this.no = no; + this.distance = distance; + } + @Override + public int compareTo(Vertex o) { + return Integer.compare(this.distance,o.distance); + } + } + + static int N,M,X; + + public static void main(String[] args) throws IOException { + final int INFINITY = Integer.MAX_VALUE; + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + M = Integer.parseInt(line[1]); + X = Integer.parseInt(line[2]); + + List[] adjListFromX = new LinkedList[N+1]; // + List[] adjListToX = new LinkedList[N+1]; + + for(int i=1; i(); // 0번 인덱스는 사용x + adjListToX[i] = new LinkedList(); // 0번 인덱스는 사용x + } + + for(int i=0; i pq = new PriorityQueue(); + Vertex current = null; + + // distFromX 채우기 + pq.offer(new Vertex(X, 0)); // 시작점을 pq에 삽입 + while(!pq.isEmpty()) { + current = pq.poll(); + if(visitedFromX[current.no]) continue; // 이미 방문한 곳이면 pass + visitedFromX[current.no] = true; + + for(int i=0,size=adjListFromX[current.no].size(); i current.distance + v.distance) { // v를 아직 방문안했고, v까지 기존의 최적값보다 현재 선택된 노드에서 v까지 이동거리의 합이 더 작으면 + distFromX[v.no] = current.distance + v.distance; // 최솟값 갱신 + pq.offer(new Vertex(v.no, distFromX[v.no])); + } + } + } + // distToX 채우기 + pq.offer(new Vertex(X, 0)); // 시작점을 pq에 삽입 + while(!pq.isEmpty()) { + current = pq.poll(); + if(visitedToX[current.no]) continue; // 이미 방문한 곳이면 pass + visitedToX[current.no] = true; + + for(int i=0,size=adjListToX[current.no].size(); i current.distance + v.distance) { // v를 아직 방문안했고, v까지 기존의 최적값보다 현재 선택된 노드에서 v까지 이동거리의 합이 더 작으면 + distToX[v.no] = current.distance + v.distance; // 최솟값 갱신 + pq.offer(new Vertex(v.no, distToX[v.no])); + } + } + } + + int result = 0; + for(int i=1; i=M-1) continue; + y++; + int west = 7-east; // 동쪽의 반대편인 서쪽 + east = up; + up = west; + }else if(d==2) { // 서 + if(y<=0) continue; + y--; + int down = 7-up; // 위쪽의 반대편인 아래쪽 + up = east; + east = down; + }else if(d==3) { // 북 + if(x<=0) continue; + x--; + int south = 7-north; // 북쪽의 반대편인 남쪽 + north = up; + up = south; + }else { // 남 + if(x>=N-1) continue; + x++; + int down = 7-up; // 위쪽의 반대편인 아래쪽 + up = north; + north = down; + } + if(map[x][y]==0) map[x][y]=dice[7-up]; // 지도에 0이면 아랫면의 숫자를 바닥에 저장 + else { // 지도에 0이 아니면 그 숫자를 주사위 아랫면에 저장 후 지도는 0으로 표시 + dice[7-up]=map[x][y]; + map[x][y]=0; + } + System.out.println(dice[up]); // 위쪽면에 저장된 숫자를 출력 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week18/Baekjoon_16637.java" "b/src/\352\260\225\353\217\231\354\204\235/week18/Baekjoon_16637.java" new file mode 100644 index 0000000..a6a35a7 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week18/Baekjoon_16637.java" @@ -0,0 +1,49 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 괄호 추가하기 +/* + * 숫자를 앞에서부터 1개 혹은 2개먼저 연산한 결과를 차근차근 연산하면 된다. + * 생각보다 문제가 너무 간단해서 골드3이라고 하기에는 쉬운 편이었다. + */ +public class Baekjoon_16637 { + + static int N,numOfNumber,result; + static int[] calcArr; + static String sentence; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); // N은 무조건 홀수 + sentence = br.readLine(); + numOfNumber = N/2+1; // 숫자의 갯수 + calcArr = new int[N/2]; // index번째 연산자 앞뒤의 수를 연산한 결과를 저장, 연산자 갯수만큼 생성 + for(int i=1,length=sentence.length(); in+1) answer = n+1; // 최솟값 갱신 + return; // 더 이상 진행할 필요 없으므로 종료 + } + + // 둘 다 구멍에 안빠지면 + + // R과B 모두 이동을 하지 않으면 무시, 백트랙킹 + if(posR[0]==nextR[0] && posR[1]==nextR[1] && posB[0]==nextB[0] && posB[1]==nextB[1]) continue; + // R과 B중 하나라도 이동을 했으면 다음단계로 진행 + dfs(n+1, nextR, nextB, d); // 횟수 1증가시킨 후 이동한 방향과 좌표를 dfs에 적용 + } + } + + public static int[] move(int[] posR, int[] posB, int d) { + int[] nextR,nextB; // 빨간구슬과 파란구슬의 다음위치 저장 + if(d==0) { // 상 + if(posR[0]<=posB[0]) { + nextR = moveOneDir(posR, posB, d); + nextB = moveOneDir(posB, nextR, d); + }else { + nextB = moveOneDir(posB, posR, d); + nextR = moveOneDir(posR, nextB, d); + } + }else if(d==1) { // 우 + if(posR[1]>=posB[1]) { + nextR = moveOneDir(posR, posB, d); + nextB = moveOneDir(posB, nextR, d); + }else { + nextB = moveOneDir(posB, posR, d); + nextR = moveOneDir(posR, nextB, d); + } + }else if(d==2) { // 하 + if(posR[0]>=posB[0]) { + nextR = moveOneDir(posR, posB, d); + nextB = moveOneDir(posB, nextR, d); + }else { + nextB = moveOneDir(posB, posR, d); + nextR = moveOneDir(posR, nextB, d); + } + }else { // 좌 + if(posR[1]<=posB[1]) { + nextR = moveOneDir(posR, posB, d); + nextB = moveOneDir(posB, nextR, d); + }else { + nextB = moveOneDir(posB, posR, d); + nextR = moveOneDir(posR, nextB, d); + } + } + return new int[] {nextR[0],nextR[1],nextB[0],nextB[1]}; // 앞에 2개는 R, 뒤에 2개는 B의 좌표 + } + + /** + * @param movePos : 움직이는 구슬 좌표 + * @param stopPos : 정지해있는 나머지 한 구슬의 좌표 + * @param d : 이동방향 + * @return : 구멍에 빠지면 {-1,-1}, 아니면 이동한 좌표를 리턴 + */ + public static int[] moveOneDir(int[] movePos, int[] stopPos, int d) { + int r = movePos[0]; // 현재 행 + int c = movePos[1]; // 현재 열 + int nr = r+dir[d][0]; // 다음 행 + int nc = c+dir[d][1]; // 다음 열 + while(true) { + if(map[nr][nc]=='O') return new int[] {-1,-1}; // 구멍에 빠지면 {-1,-1} 리턴 + if(map[nr][nc]!='.' || (nr==stopPos[0] && nc==stopPos[1])) break; // 빈칸이 아니거나 다른 구슬과 위치가 겹치면 종료 종료 + r = nr; c = nc; // 한칸이동 + nr += dir[d][0]; // 다음 행 + nc += dir[d][1]; // 다음 열 + } + return new int[] {r,c}; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_17281.java" "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_17281.java" new file mode 100644 index 0000000..d9a8e5d --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_17281.java" @@ -0,0 +1,79 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/* + * 순열을 이용하여 최대 50이닝 이므로 8! * 50 = 2,016,000 이어서 시간초과가 발생하지 않을 줄 알았는데, + * 처음에 주자들이 전진하는 과정에서 큐를 사용하였다가 시간초과가 발생하였다. + * 이후 boolean배열로 수정해서 관리하여 해결하였다. + * 아마 최악의 경우 한 이닝당 최대 27명의 타자가 존재하므로 + * 2,016,000 * 27 = 54,432,000 이기때문에 큐를 사용하면 overhead가 커서 아슬아슬하게 시간초과가 발생하는것 같다는 생각이 든다. + */ +public class Baekjoon_17281 { + + static int N,totalScore,result,orderIdx; + static int[] order = new int[9]; // 선수들의 번호들이 타순으로 저장된 배열, 항상 order[3]=0은 고정 + static boolean[] used = new boolean[9]; + static int[][] points; // 각 이닝에서 선수들이 얻는 결과 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line; + N = Integer.parseInt(br.readLine()); + points = new int[N][9]; + for(int i=0; i=0; --i) { + if(base[i]) {// 주자가 존재하면 + if(i+hit>=4) totalScore++; // 주자가 홈에 들어오면 1점 획득 + else base[i+hit]=true; // 주자가 홈에 못들어오면 주자 위치를 이동 + base[i]=false; // 원래 있던 자리 비우기 + } + } + } + orderIdx = (orderIdx+1)%9; // 타자의 순서는 다음타자로 변경 + if(outCount==3) break; // 3번 아웃이면 현재 이닝 종료 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2110.java" "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2110.java" new file mode 100644 index 0000000..5b3ea36 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2110.java" @@ -0,0 +1,49 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +// 공유기 설치 +/* + * 공유기 마다 무조건 거리를 두어야 하는 최소거리를 이분탐색으로 변경해가며 + * 공유기가 모두 설치 가능한지 여부를 판단하는 것이 이 문제의 핵심인 것 같다. + * 이분탐색은 아직 익숙치 않아서 그런지 감이 잘 안잡혀서 구글링을 참고하였다. + * 시간복잡도: O(NlogN) N크기의 배열을 이분 탐색을 통해 logN 횟수만큼 반복문을 순회한다. + */ +public class Baekjoon_2110 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + int N = Integer.parseInt(line[0]); + int C = Integer.parseInt(line[1]); + int[] arr = new int[N]; + for(int i=0; i=mid) { // i번째 집과 직전 공유기와의 거리가 최소거리 이상 이면 + prev=arr[i]; + count++; // 공유기 설치 + } + } + if(count>=C) { // C개의 공유기를 충분히 다 설치할 수 있다면 + low = mid+1; // 왼쪽경계 변경 + result = mid; // 답 갱신 + }else { // C개의 공유기를 다 설치하지 못한다면 + high = mid-1; // 오른쪽경계 변경 + } + } + System.out.println(result); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2212.java" "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2212.java" new file mode 100644 index 0000000..e01c62e --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week19/Baekjoon_2212.java" @@ -0,0 +1,39 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +// 센서 +/* + * 센서들을 오름차순 정렬한 후, 센서들 사이의 거리를 저장하는 배열을 만든다. + * 그리고 집중국이 처음에 다 연결되어있다고 가정하고, + * K-1개만큼의 연결을 끊어야 K개만큼 집중국의 갯수가 나오므로, + * 센서들 사이의 거리를 저장한 배열을 오름차순 정렬 후, + * 뒤에서부터 길이가 가장 긴 부분을 K-1개 만큼 제외한 나머지 길이의 합을 구한다. + */ +public class Baekjoon_2212 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int K = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + String[] line = br.readLine().split(" "); + for(int i=0; i map = new HashMap(); + String[] split1 = s.split("\\},\\{"); + int length = split1.length; + if(length==1) { // 원소의 갯수가 하나면 + return new int[] {Integer.parseInt(split1[0].substring(2, split1[0].length()-2))}; + } + String[] split2 = split1[0].substring(2).split(","); // "{{n1,n2,..." 에서 앞쪽의 "{{"를 제거한 후 콤마(,)로 다시 나눈다. + for(int i=0,len2=split2.length; i0) numOfAlphabet++; // 알파벳이 등장한 갯수 카운트 + } + if(K>=numOfAlphabet) { // + System.out.println(N); + return; + } + result = 0; + combination(0,0); // 조합 + System.out.println(result); + } + + public static void combination(int n, int idx) { // 현재 n개 알파벳 선택, idx번째 알파벳 부터 확인 + if(n==K-5) { // K-5개의 알파벳을 선택하였으면 (a,c,i,n,t는 제외) + countWords(); + return; + } + if(K-5-n+idx>26) { // 남은 알파벳을 전부 선택해도 K개를 선택할 수 없다면 종료 + return; + } + + for(int i=idx; i<26; ++i) { // 알파벳 26개에 대하여 + if(i==0 || i==2 || i==8 || i==13 || i==19) continue; // a,c,i,n,t이면 선택안함 + if(alphabetCnt[i]>0) { // idx번째 알파벳이 한 번이라도 등장했으면 + learned[i]=true; // 선택 + combination(n+1, i+1); // 다음 알파벳 선택 + learned[i]=false; // 선택 해제 + } + } + } + + public static void countWords() { + int count = 0; // 읽을 수 있는 단어의 총 갯수 + for(int i=0; i=K) { // mid보다 작거나 같은 숫자들의 갯수가 K개 이상이면 + high=mid; // 상한선이 답이 될지도 모르므로 mid로 조정 + }else { // mid보다 작거나 같은 숫자들의 갯수가 K개 보다 작으면 + low=mid+1; // 하한선이 답이 될 수는 없으므로 mid+1로 조정 + } + } + System.out.println(low); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_16234.java" "b/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_16234.java" new file mode 100644 index 0000000..68cd81c --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_16234.java" @@ -0,0 +1,90 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +// 인구 이동 +/* + * bfs를 이용하여 조건에 맞느 연합을 찾은 후 인구 이동을 시키고 visited배열을 이용하여 방문체크를 한다. + * N*N을 한번 모두 체크한 후 특정 값을을 초기화하여 이동이 일어나지 않을때까지 반복한다. + * 시간복잡도: O(N^2) 더 이상 인구 이동이 없을 떄 까지 매번 N*N배열을 전부 확인한다. + */ +public class Baekjoon_16234 { + + static int N,L,R,result; + static int[][] map; + static boolean isMoved; // 인구이동 여부 + static boolean[][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + L = Integer.parseInt(line[1]); + R = Integer.parseInt(line[2]); + map = new int[N][N]; + for(int i=0; i q = new LinkedList(); + q.offer(new int[] {x,y}); + + ArrayList union = new ArrayList(); // 연합의 좌표를 담을 리스트 + int sumOfUnion = 0; // 연합의 총 인구수 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + int curNum = map[r][c]; // 현재 위치의 인구수 + + if(visited[r][c]) continue; // 이미 방문했으면 무시 + visited[r][c] = true; // 방문표시 + union.add(new int[] {r,c}); // 연합에 좌표 저장 + sumOfUnion+=curNum; // 연합의 총 인구수에 더하기 + + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; // 다음 행 + int nc = c+dir[d][1]; // 다음 열 + if(nr<0 || nc<0 || nr>=N || nc>=N) continue; // 경계 밖이면 무시 + if(visited[nr][nc]) continue; // 이미 방문했으면 무시 + int nextNum = map[nr][nc]; // 다음 위치의 인구수 + int gap = Math.abs(nextNum-curNum); + if(gap>=L && gap<=R) q.offer(new int[] {nr,nc}); // 인구 차이가 L이상 R이하이면 큐에 저장 + } + } + if(union.size()==1) return; // 연합을 이루는 나라가 1개밖에 없으면 종료 + isMoved=true; // 연합을 이루는 나라가 2개 이상이면 인구이동 + int averageNum = sumOfUnion/union.size(); // 이동 후 인구수 = (연합의 인구수) / (연합을 이루고 있는 칸의 개수) + for(int[] pos : union) { + map[pos[0]][pos[1]] = averageNum; // 인구 이동 후 평균 인구수로 조정 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_2533.java" "b/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_2533.java" new file mode 100644 index 0000000..c311e7d --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week20/Baekjoon_2533.java" @@ -0,0 +1,60 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 사회망 서비스(SNS) +/* + * 본인이 얼리 어답터일때와 아닐때 두 경우를 나누어서 생각하면 된다. + * 본인이 맞을때는 자식은 맞을수도 있고 아닐수도 있는 모든 경우 중에 최솟값을 구하면 되고, + * 본인이 아닐때는 자식이 모두 맞는 경우만 생각하면 된다. + * dp일 것 같다는 생각은 들었지만, 트리 구조에서 dp를 적용시키는게 익숙하지 않았다. + * 결국 구글링하여 다른 풀이를 참고하였다. + * 아직 dp의 길은 멀고도 험하구나... + */ +public class Baekjoon_2533 { + + static boolean[] visited; + static ArrayList[] adjList; // 인접리스트 + static int[][] dp; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); // 색종이 수 + visited = new boolean[N+1]; + dp = new int[N+1][2]; + adjList = new ArrayList[N+1]; + for(int i=1; i(); + } + + String[] line; + for(int i=1; i를 이용하여 설정하는 방법을 배웠다. + * union-find 방법으로도 풀어봐야겠다! + */ +public class Baekjoon_11085 { + + static int p,w,c,v; + static int[] distance; + static boolean[] visited; + static ArrayList[] adjList; // 인접리스트 + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + p = Integer.parseInt(line[0]); + w = Integer.parseInt(line[1]); + line = br.readLine().split(" "); + c = Integer.parseInt(line[0]); + v = Integer.parseInt(line[1]); + + distance = new int[p]; + Arrays.fill(distance, Integer.MAX_VALUE); // 최솟값을 구하기 위해 초기화 + visited = new boolean[p]; + adjList = new ArrayList[p]; + for(int i=0; i(); + } + + for(int i=0; i pq = new PriorityQueue(new Comparator() { // {시작점, 도착점, 길의 너비} 저장 + @Override + public int compare(int[] o1, int[] o2) { + return Integer.compare(o2[2], o1[2]); // 거리기준 내림차순 정렬 + } + }); + + pq.add(new int[] {c,c,Integer.MAX_VALUE}); // 제일 처음 값은 이후 최솟값 갱신시 비교하는 과정에 영향을 미치기 때문에 문제 조건에 따라 1000이상으로 초기화 + + while(!pq.isEmpty()) { + int[] cur = pq.poll(); + int from = cur[0]; // 시작점 + int to = cur[1]; // 도착점 + int dist = cur[2]; // 길의 너비 + + if(visited[to]) continue; // 이미 방문했으면 무시 + visited[to] = true; // 방문체크 + + distance[to] = Math.min(dist, distance[from]); // 기존의 출발점까지의 최솟값과 비교 후 도착점까지의 최솟값을 갱신 + + if(to==v) break; // v 지점까지 도달했으면 종료 + + for(int[] info : adjList[to]) { + if(visited[info[0]]) continue; // 이미 방문했으면 무시 + pq.add(new int[]{to, info[0], info[1]}); // to를 시작점으로 한 새로운 길들을 pq에 담기 + } + } + System.out.println(distance[v]); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week21/Baekjoon_1700.java" "b/src/\352\260\225\353\217\231\354\204\235/week21/Baekjoon_1700.java" new file mode 100644 index 0000000..be6032c --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week21/Baekjoon_1700.java" @@ -0,0 +1,72 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 멀티탭 스케줄링 +/* + * 새로 바꿀것이 있으면 기존의 어떤 것과 바꿀것인지 선택하는 로직이 핵심이다. + * 새로 바꿀것 다음부터 순서대로 체크하여 기존에 사용중인 것이면 바꾸지 않게 체크하다가 + * 기존 사용중인 것 중에 마지막 하나 체크가 안된것을 바꾸는 방법으로 구현하였다. + * 시간복잡도: O(N^2) 이지만 N이 최대 100이므로 시간고려 안해도 됨. + */ +public class Baekjoon_1700 { + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + int N = Integer.parseInt(line[0]); + int K = Integer.parseInt(line[1]); + boolean[] used = new boolean[K+1]; // 0번은 미사용 + int usedCnt = 0; // 현재 몇개의 어댑터가 사용중인지 + int result=0; + line = br.readLine().split(" "); + for(int i=0; i=result) return; // 기존의 최솟값보다 크면 종료 + + if(c>9) { // 행의 마지막 열까지 다 확인했으면 + dfs(r+1,0,count); // 다음 행의 첫칸부터 확인 + }else { + if(map[r][c]==1) { // 현재 칸을 덮을 수 있으면 + for(int size=5; size>=1; --size) { + if(papersLeft[size]>0&&canCover(r, c, size)) { // 1이고 size크기의 색종이로 덮을 수 있으면 + papersLeft[size]--; // 남은 색종이 수 1 감소 + cover(r, c, size, 0); // 덮기 + + dfs(r,c+size,count+1); // 다음 칸부터 시작하고 사용한 색종이 수 1증가 + + papersLeft[size]++; // 남은 색종이 수 1 증가 + cover(r, c, size, 1); // 덮기 취소 + } + } + }else { // 현재 칸을 덮을 수 없으면 + dfs(r,c+1,count); // 다음 칸 확인 + } + } + } + + public static boolean canCover(int r, int c, int size) { + for(int i=r; i=10 || j<0 || j>=10) return false; // 경계 체크 + if(map[i][j]!=1) return false; // 덮을 수 없는 곳이면 false + } + } + return true; + } + + public static void cover(int r, int c, int size, int n) { + for(int i=r; i a번째 칸까지 b개를 채우는 경우의 수 => W가 a번 나올 때 H를 b개 채우는 경우의 수 + * dp[a][b] = dp[a-1][1] + dp[a-1][2] + dp[a-1][3] + ... + dp[a-1][b] (a>b일 때) + * dp[a][b] = dp[a][b-1] (a==b일 때) + */ +public class Baekjoon_4811 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + long[][] dp = new long[31][31]; + for(int i=1; i<=30; ++i) { + dp[i][1] = i; // 1열 전부 초기화 + } + for(int i=2; i<=30; ++i) { + for(int j=2; j'9') { // 숫자가 아니면 + head.append(ch); // head에 추가 + } else { // 아니면 종료 + break; + } + } + StringBuilder number = new StringBuilder(); + for(int k=pointer; k='0' && ch<='9') { // 숫자이면 + number.append(ch); // number에 추가 + } else { // 숫자가 아니면 종료 + break; + } + } + infos[i][0]=head.toString().toLowerCase(); // HEAD에 비교를 위해 소문자로 모두 변환 후 저장 + infos[i][1]=number.toString(); // NUMBER 저장 + infos[i][2]=String.valueOf(i); // 원래 인덱스 저장 + } + Arrays.sort(infos, new Comparator() { + + @Override + public int compare(String[] o1, String[] o2) { + if(o1[0].equals(o2[0])) { // HEAD가 같으면 + return Integer.compare(Integer.parseInt(o1[1]), Integer.parseInt(o2[1])); // NUMBER순 오름차순 + }else { + return o1[0].compareTo(o2[0]); // HEAD기준 사전순 정렬 + } + } + }); + String[] answer = new String[numOfFile]; + for(int i=0; i{ + int from; + int to; + int weight; + + public Edge(int from, int to, int weight) { + super(); + this.from = from; + this.to = to; + this.weight = weight; + } + + @Override + public int compareTo(Edge o) { + return Integer.compare(this.weight, o.weight); + } + + } + + static Edge[] edgeList; + static int[] parents; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + int V = Integer.parseInt(line[0]); + int E = Integer.parseInt(line[1]); + + edgeList = new Edge[E]; + for(int i=0; i=K) { + System.out.println(N-K); + System.out.println(1); + return; + } + Queue q = new LinkedList(); + q.offer(N); // 시작점 삽입 + int resultTime = 0; // 가장 빠른 시간 + int resultCnt = 0; // 가장 빠른 방법 수 + Set visitedPos = new HashSet(); + while(!q.isEmpty()) { + int size = q.size(); + while(size-->0) { // pq에서 같은 depth에 있는 것만 확인 + int pos = q.poll(); + if(pos<0 || pos > 100000) continue; // 범위 밖이면 무시 + if(visited[pos]) continue; // 이미 확인한 지점이면 무시 + visitedPos.add(pos); // 현재 지점을 set에 추가 + if(pos==K) { // K에 도착했으면 + resultCnt++; // 도착 방법 수 1 증가 + }else { // K에 도착하지 않았으면 + q.offer(pos-1); // X-1로 이동 + q.offer(pos+1); // X+1로 이동 + q.offer(pos*2); // X*2로 이동 + } + } + if(resultCnt>0) break; // 같은 depth에서 하나라도 도착을 했으면 바로 종료 + resultTime++; // 시간 1초 경과 + for(int n : visitedPos) { + visited[n]=true; // 방문한 곳들 한번에 체크 + } + visitedPos.clear(); // 초기화 + } + System.out.println(resultTime); + System.out.println(resultCnt); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_14950.java" "b/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_14950.java" new file mode 100644 index 0000000..2cf9c87 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_14950.java" @@ -0,0 +1,70 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 정복자 +/* + * prim 알고리즘을 연습해볼겸 적용하여 해결하려고 하였으나 + * 처음에 인접행렬을 사용하여 메모리초과... + * 그 다음에 인접리스트를 이용하여 해결하였다. + * prim 알고리즘의 시간복잡도: O(V^2) + * kruskal 알고리즘의 시간복잡도: O(ElogE) + */ +public class Baekjoon_14950 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + int N = Integer.parseInt(str[0]); + int M = Integer.parseInt(str[1]); + int t = Integer.parseInt(str[2]); + + boolean[] visited = new boolean[N+1]; + + ArrayList[] adjList = new ArrayList[N+1]; // {도착점, 가중치} + for(int i=1; i(); + } + for(int i=0; iminWeight[j]) { + min = minWeight[j]; + minVertex=j; + } + } + visited[minVertex]=true; // 방문체크 + totalWeight+=min; // 가중치의 합 계산 + for(int[] arr : adjList[minVertex]) { + int nextV = arr[0]; // 새로운 정점 + int nextW = arr[1]; // 새로운 가중치 + if(!visited[nextV] && nextW < minWeight[nextV]) { + minWeight[nextV] = nextW; + } + } + } + totalWeight+=(N-2)*(N-1)/2*t; + System.out.println(totalWeight); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_2933.java" "b/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_2933.java" new file mode 100644 index 0000000..e7b3fd6 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week22/Baekjoon_2933.java" @@ -0,0 +1,164 @@ +package baekjoon; + +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 Baekjoon_2933 { + + static int R,C,N; + static int turn; // 왼쪽, 오른쪽 중 어느 방향에서 던지는지 (0:왼, 1:오) + static int fallDist; // 클러스터가 떨어지는 거리 + static char[][] map; + static ArrayList clusterPos; // 한 클러스터의 좌표들을 저장 + static boolean[][] sameGroupCheck; // 같은 클러스터의 미네랄 표시 + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + R = Integer.parseInt(line[0]); + C = Integer.parseInt(line[1]); + map = new char[R][C]; + for(int i=0; i(); + N = Integer.parseInt(br.readLine()); + turn = 0; // 시작은 왼쪽부터 던짐 + StringTokenizer st = new StringTokenizer(br.readLine()," "); + while(st.hasMoreTokens()) { + int height = Integer.parseInt(st.nextToken()); + int[] point = throwStick(R-height); // 바닥부터 1이므로 인덱스를 뒤에서부터 계산한다 + if(point[0]<0) { // 충돌하지 않으면 다음 차례 + turn ^= 1; // 왼쪽, 오른쪽 던지는 순서 바꿈 + continue; + } + if(canClusterFall(point)) { // 떨어질 클러스터가 존재하면 + fallCluster(); // 클러스터 떨어뜨리기 + } + turn ^= 1; + } + for(char[] ar : map) { + for(char a : ar) { + System.out.print(a); + } + System.out.println(); + } + } + + public static int[] throwStick(int height) { // 막대기를 던져 충돌지점 미네랄 제거 및 충돌지점을 반환 + int[] crossPoint = new int[] {-1,-1}; // 막대기와 미네랄의 충돌지점, {-1,-1}로 초기화 + if(turn==0) { // 왼쪽에서 던짐 + for(int c=0; c=0; --c) { + if(map[height][c]=='x') { // 미네랄과 충돌하면 + map[height][c]='.'; + crossPoint[0] = height; + crossPoint[1] = c; + break; + } + } + } + return crossPoint; + } + + public static boolean canClusterFall(int[] point) { // 떨어지는 클러스터가 있는지 체크 + boolean exist = false; // 존재 안함으로 초기화 + if(checkClusterPos(new int[] {point[0]-1, point[1]})) { // 충돌지점 윗칸 클러스터 체크 + exist=true; + }else if(checkClusterPos(new int[] {point[0]+1, point[1]})) { // 충돌지점 아랫칸 클러스터 체크 + exist=true; + }else { // 좌,우 중 한곳 체크 + if(turn==0) { // 왼쪽에서 던졌으면 오른쪽칸 체크 + if(checkClusterPos(new int[] {point[0], point[1]+1})) exist=true; + }else { // 오른쪽에서 던졌으면 왼쪽칸 체크 + if(checkClusterPos(new int[] {point[0], point[1]-1})) exist=true; + } + } + return exist; + } + + public static boolean checkClusterPos(int[] point) { // point가 속해있는 클러스터의 모든 좌표들을 확인 + if(point[0]<0 || point[1]<0 || point[0]>=R || point[1]>=C) return false; // 경계 벗어나면 false + if(map[point[0]][point[1]]=='.') return false; // 해당 칸이 빈칸이면 false + Queue q = new LinkedList(); + q.offer(point); + + boolean[][] visited = new boolean[R][C]; + clusterPos.clear(); // 기존의 좌표들 초기화 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(r==R-1) return false; // 바닥에 붙어있는 미네랄이 있으면 false + + if(visited[r][c]) continue; + visited[r][c]=true; // 방문 체크 + clusterPos.add(new int[] {r,c}); // 클러스터의 미네랄 좌표들을 저장 + + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nc<0 || nr>=R || nc>=C) continue; // 다음좌표 경계 체크 + if(map[nr][nc]=='x') { // 다음 칸이 미네랄이면 + q.offer(new int[] {nr,nc}); + } + } + } + + fallDist=999; // 떨어지는 최소 거리 초기화 + sameGroupCheck = new boolean[R][C]; // 같은 클러스터는 true + for(int[] position : clusterPos) { // 각 미네랄 지점마다 + sameGroupCheck[position[0]][position[1]]=true; // 같은 클러스터의 미네랄 체크 + } + for(int[] pos : clusterPos) { + fallDist = Math.min(fallDist, calcFallHeight(pos)); // 떨어지는 거리 계산하여 갱신 + } + return true; // 공중에 떠있는 클러스터의 미네랄 좌표들을 저장 후 true 리턴 + } + + public static int calcFallHeight(int[] pos) { + int r = pos[0]+2; // 2칸 아래 + int c = pos[1]; + int dist = 1; // 최소 떨어지는 거리는 1 + for(; r map1 = new HashMap(); + Map map2 = new HashMap(); + + for(int i=0,len=str1.length(); i keySet1 = map1.keySet(); + Set keySet2 = map2.keySet(); + + int commonCnt = 0; // 교집합의 크기 + for(String key : keySet1) { + commonCnt += Math.min(map1.get(key), map2.getOrDefault(key, 0)); + } + + int totalCnt = 0; // 합집합의 크기 + for(String key : keySet1) { + totalCnt += map1.get(key); // 집합1의 원소 수 다 더하기 + } + for(String key : keySet2) { + totalCnt += map2.get(key); // 집합2의 원소 수 다 더하기 + } + if(totalCnt==0) return 65536; // 둘 다 공집합이면 1로 처리 + totalCnt -= commonCnt; // 교집합의 수만큼 뺴주기 + + int answer = (int)((double)commonCnt/totalCnt*65536); + return answer; + } + + public static boolean isAlphabet(String str) { + return str.charAt(0) >= 'a' && str.charAt(0) <= 'z' && str.charAt(1) >= 'a' && str.charAt(1) <= 'z'; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week23/Baekjoon_1043.java" "b/src/\352\260\225\353\217\231\354\204\235/week23/Baekjoon_1043.java" new file mode 100644 index 0000000..d842f68 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week23/Baekjoon_1043.java" @@ -0,0 +1,66 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.Set; + +// 거짓말 +/* + * set을 이용하여 파티원들을 묶고, boolean배열을 이용하여 진실을 아는 사람들을 체크하며 + * 해당 파티에 한명이라도 진실을 하는자가 있으면, 그 파티원 모두 진실을 알게 저장한 후, 진실을 말해야만 하는 파티를 + * allTruth라는 boolean배열을 통해서 체크하고, 거짓말을 해도 되는 파티의 수만 세어서 답을 구한다. + */ +public class Baekjoon_1043 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + int N = Integer.parseInt(line[0]); + int M = Integer.parseInt(line[1]); + + boolean[] truth = new boolean[N+1]; // 진실을 아는 사람의 번호 + boolean[] allTruth = new boolean[M]; // 모두가 진실을 아는 파티번호 + Set[] partySet = new HashSet[M]; + for(int i=0; i(); + } + + line = br.readLine().split(" "); + int truthNum = Integer.parseInt(line[0]); + for(int i=1; i<=truthNum; ++i) { + truth[Integer.parseInt(line[i])]=true; // 사실을 아는사람 체크 + } + + for(int i=0; i set = partySet[i]; + for(int personNum : set) { + if(truth[personNum]) { // 해당 파티에 진실을 아는 사람이 존재하면 + for(int num : set) { + truth[num]=true; // 해당 파티의 모든 사람이 진실을 알게 체크 + } + allTruth[i]=true; // 모두가 사실 확인 체크 + break; + } + } + } + } + + int result = 0; + for(int i=0; i q = new LinkedList(); + q.add(new int[] {startR,startC,0,0}); // 행,열,이동횟수,key보유 비트마스킹 + + // 열쇠를 몇개 들고 그 위치를 방문했는지를 체크하는 visited 배열 생성 + boolean[][][] visited = new boolean[N][M][1<<6]; // 알파벳 6개 이므로 비트마스킹을 위해 1<<(0~5)를 다 담기 위해 1<<6 만큼 생성 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r=cur[0]; // 행 + int c=cur[1]; // 열 + int cnt=cur[2]; // 이동횟수 + int key=cur[3]; // key보유상태 + + if(cnt>=result || visited[r][c][key]) continue; // 현재 이동거리가 기존 최솟값 이상이거나 이미 방문한 곳이면 가지치기 + visited[r][c][key] = true; // 해당 좌표를 해당키 보유상태로 방문 표시 + + // 4방탐색 + for(int i=0; i<4; i++) { + int nr=r+dir[i][0]; + int nc=c+dir[i][1]; + if(isValid(nr,nc)) { // 갈 수 있는 칸이면 + char ch = map[nr][nc]; + if(ch>='a' && ch<='f') { // 해당칸이 열쇠이면 + int newKey = key | 1<<(ch-'a'); + q.offer(new int[] {nr,nc,cnt+1,newKey}); // 다음칸의 정보를 큐에 추가 + }else if(ch>='A' && ch<='F') { // 해당칸이 문이면 + if(canOpen(key,ch)) { // 문을 열 수 있으면 + q.offer(new int[] {nr,nc,cnt+1,key}); + } + }else if(ch=='1'){ // 도착했으면 이동횟수 최솟값 갱신 + if(result>cnt+1) result = cnt+1; + }else { // 해당칸이 일반 칸이면 + q.offer(new int[] {nr,nc,cnt+1,key}); + } + } + } + } + } + public static boolean isValid(int r, int c) { // 경계 및 벽 체크 + if(r>=0 && r=0 && c 0) return true; // 비트연산이 하나라도 일치하면 1이상이므로 + return false; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_42842.java" "b/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_42842.java" new file mode 100644 index 0000000..0257d4d --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_42842.java" @@ -0,0 +1,23 @@ +package programmers; + +// 카펫 +public class Programmers_42842 { + + public static void main(String[] args) { + int brown = 24; + int yellow = 24; + System.out.println(solution(brown, yellow)[0]); + } + + public static int[] solution(int brown, int yellow) { + int n = brown/2-2; + int garo = n%2==0?n/2:n/2+1; + int sero = 0; + for(; garo=n) { // 검사를 다 하고 남으면 + answer=mid; + high = mid-1; + }else { // 검사를 다 못하는 경우 + low = mid+1; + } + } + return answer; + } + +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_84021.java" "b/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_84021.java" new file mode 100644 index 0000000..28b5d7f --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week23/Programmers_84021.java" @@ -0,0 +1,181 @@ +package programmers; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +// 퍼즐 조각 채우기 +/* + * game_board에서 빈칸 정보들을 list로 얻고, table에서 블럭 정보들을 list로 얻은 후 비교한다. + * 비교할 때 회전했을 때 일치하는지 여부는 판단하지 않고 있는 그대로 비교한다. 그리고 일치하는 블럭들은 다 상쇄시킨 후 + * table을 90도 회전하여 다시 블럭 정보들을 list로 얻은 후 비교한다. 이런식으로 270도 까지 회전시켜 모두 비교한다. + */ +public class Programmers_84021 { + + public static void main(String[] args) { + int[][] game_board = {{0,0,1,0,0,1},{1,0,1,1,0,1},{1,0,0,1,0,0},{1,1,1,1,1,1},{1,1,1,1,1,1},{1,1,1,1,1,1}}; + int[][] table = {{1,0,0,1,1,0},{1,0,1,0,1,0},{0,1,1,0,1,1},{0,0,1,0,0,0},{1,1,0,1,1,0},{0,1,0,0,0,0}}; + System.out.println(solution(game_board, table)); + } + + static class Block { + int num; // 블럭의 칸 갯수 + int[] startPos; // 시작점의 좌표 + List posList; // 블럭을 이루는 칸들의 좌표 + + public Block(int num, int[] startPos, List posList) { + this.num = num; + this.startPos = startPos; + this.posList = posList; + } + } + + static int N,answer; + static boolean[][] visited; // 회전할떄마다 초기화 하기 + static int[][] table_static; + static List gameBlockList; // game_board의 빈칸들의 정보 + static List tableBlockList; // table의 블럭들의 정보 + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static int solution(int[][] game_board, int[][] table) { + table_static = table; + N = game_board.length; + + gameBlockList = new ArrayList<>(); // game_board의 빈칸들의 정보 + for(int i=0; i list = getBlocksFromGameBoard(i,j,game_board); + gameBlockList.add(new Block(list.size(), new int[] {i,j}, list)); // 블럭 추가 + } + } + } + + tableBlockList = new ArrayList<>(); + settingTableInfo(); + matchBlock(); + + rotateTable90(); // table을 90도 시계방향 회전 + settingTableInfo(); + matchBlock(); + + rotateTable90(); // table을 90도 시계방향 회전 + settingTableInfo(); + matchBlock(); + + rotateTable90(); // table을 90도 시계방향 회전 + settingTableInfo(); + matchBlock(); + + return answer; + } + + public static void rotateTable90() { + int[][] copied = new int[N][N]; + for(int i=0; i list = getBlocksFromTable(i,j,table_static); + tableBlockList.add(new Block(list.size(), new int[] {i,j}, list)); // 블럭 추가 + } + } + } + } + + public static void matchBlock() { + for(int idx=0; idx getBlocksFromGameBoard(int i, int j, int[][] board) { + Queue q = new LinkedList(); + q.offer(new int[] {i,j}); + List posList = new ArrayList(); // 칸의 좌표들 저장 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if(board[r][c]==1) continue; // 이미 채워져 있으면 무시 + board[r][c]=1; // 채우기 + posList.add(new int[] {r-i,c-j}); // 첫 번째 칸을 {0,0} 기준으로 변환하여 좌표 저장 + + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nc<0 || nr>=N || nc>=N) continue; // 경계 체크 + if(board[nr][nc]==0) { // 다음칸이 빈칸이면 + q.offer(new int[] {nr,nc}); // 큐에 추가 + } + } + } + + return posList; + } + + public static List getBlocksFromTable(int i, int j, int[][] board) { + Queue q = new LinkedList(); + q.offer(new int[] {i,j}); + List posList = new ArrayList(); // 칸의 좌표들 저장 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if(visited[r][c]) continue; // 방문체크 + visited[r][c] = true; // 방문표시 + posList.add(new int[] {r-i,c-j}); // 첫 번째 칸을 {0,0} 기준으로 변환하여 좌표 저장 + + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nc<0 || nr>=N || nc>=N) continue; // 경계 체크 + if(board[nr][nc]==1 && !visited[nr][nc]) { // 다음칸이 블럭이고 방문 안했으면 + q.offer(new int[] {nr,nc}); // 큐에 추가 + } + } + } + + return posList; + } + + public static boolean checkSameBlock(List list1, List list2) { + int size = list1.size(); + for(int i=0; i=K) break; + } + System.out.println(times); + } + + public static void rotate() { // 벨트 회전 + inPos = (inPos+2*N-1)%(2*N); // 올리는 위치 한 칸 이동 + outPos = (outPos+2*N-1)%(2*N); // 내리는 위치 한 칸 이동 + for(int i=N-2; i>=0; --i) { // 로봇들도 한 칸씩 이동 + if(isRobot[i]) { // 로봇이 존재하면 한 칸 이동 + isRobot[i+1]=true; + isRobot[i]=false; + } + } + isRobot[N-1]=false; // 내리는 위치의 로봇 제거 + } + + public static void moveRobots() { + for(int i=N-2; i>=0; --i) { + if(isRobot[i]) { // 로봇이 존재하면 + if(!isRobot[i+1] && conveyorBelt[(inPos+i+1)%(2*N)]>0) { // 다음 칸에 로봇이 없고 내구도가 1이상이면 + if(--conveyorBelt[(inPos+i+1)%(2*N)]==0) { // 다음칸의 내구도 1 감소 + zeroCnt++; // 내구도가 0이면 카운트 1 증가 + } + isRobot[i+1]=true; // 다음칸으로 이동 + isRobot[i]=false; + } + } + } + isRobot[N-1]=false; // 내리는 위치의 로봇 제거 + } + + public static void upRobot() { // 로봇 올리기 + if(conveyorBelt[inPos]>0) { // 내구도 1이상 남아있으면 + if(--conveyorBelt[inPos]==0) { // 내구도 1 감소 및 내구도 0 카운트 + zeroCnt++; + } + isRobot[0]=true; // 로봇 올리기 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week24/Baekjoon_2616.java" "b/src/\352\260\225\353\217\231\354\204\235/week24/Baekjoon_2616.java" new file mode 100644 index 0000000..3775428 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week24/Baekjoon_2616.java" @@ -0,0 +1,50 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 소형기관차 +/* + * dp[i][j]는 i번째 부분합까지 중에서 j+1개를 선택한 최댓값을 저장하는 방식으로 해결하였다. + * 여기서 총 3개만 선택하므로 j는 0~2까지 이다. + */ +public class Baekjoon_2616 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] train = new int[N]; + String[] line = br.readLine().split(" "); + for(int i=0; i q = new LinkedList(); + if(board[0][1]==0) { + cost[0][1] = 100; + q.offer(new int[] {0,1,RIGHT,100}); + } + if(board[1][0]==0) { + cost[1][0] = 100; + q.offer(new int[] {1,0,DOWN,100}); + } + while(!q.isEmpty()) { + int[] current = q.poll(); + int r = current[0]; // 행 + int c = current[1]; // 열 + int d = current[2]; // 방향 : 상(0),우(1),하(2),좌(3) + int sum = current[3]; // 비용합 + if(r==N-1 && c==N-1) { + if(result>sum) result = sum; + } + for(int i=0; i<4; i++) { + int nr = r+dir[i][0]; + int nc = c+dir[i][1]; + + if(nr<0 || nr>=N || nc<0 || nc>=N || board[nr][nc]!=0) continue; // 경계 및 벽 체크 + int nextSum = sum; // 다음칸까지의 비용의 합 + if(d==i) nextSum += 100; // 같은 방향이면 +100 + else nextSum += 600; // 다른 방향이면 +600(코너+직선경로) + + // 기존의 최적값이 경로를 꺾어서 갈 경우 현재 경로값이 경로를 꺾지 않으면 최대 400만큼의 비용이 더 들어와도 현재 경로가 유리하다. + if(cost[nr][nc]>=nextSum-400) { + cost[nr][nc]=nextSum; + q.offer(new int[] {nr,nc,i,nextSum}); + } + } + } + return result; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week24/Programmers_72411.java" "b/src/\352\260\225\353\217\231\354\204\235/week24/Programmers_72411.java" new file mode 100644 index 0000000..52aae78 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week24/Programmers_72411.java" @@ -0,0 +1,119 @@ +package programmers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +// 메뉴 리뉴얼 +/* + * 1. 모든 등장하는 알파벳을 체크한다. + * 2. course의 숫자만큼 알파벳 조합을 만들어 해당 코스요리를 map에 형태로 value값을 등장 횟수로 저장한다. + * 3. map에서 value가 최댓값인 key들을 List에 저장한다. + * 4. 2~3번을 끝까지 반복한다. + * 5. List을 String[]형태로 변환 후 정렬한다. + */ +public class Programmers_72411 { + + public static void main(String[] args) { + String[] orders = {"XYZ", "XWY", "WXA"}; + int[] course = {2,3,4}; + String[] arr = solution(orders, course); + for(String str : arr) { + System.out.print(str+" "); + } + } + + static int num; + static boolean[] alphabet; + static boolean[][] used; + static int[] arr; + static Map map; + static List answerList; + + public static String[] solution(String[] orders, int[] course) { + alphabet = new boolean[26]; // 알파벳 26개의 사용 여부 + used = new boolean[orders.length][26]; // 각 order마다 사용한 알파벳 체크 + map = new HashMap(); + answerList = new ArrayList(); + for(int i=0,size=orders.length; i=num) cnt++; + if(cnt>=2) break; + } + if(cnt>=2) { // 해당 길이 이상의 문자들이 2개 이상이면 + arr = new int[n]; + combination(0,0); + int max = 0; + for(String key : map.keySet()) { + max = Math.max(max, map.get(key)); + } + for(String key : map.keySet()) { + if(map.get(key)==max) { + answerList.add(key); +// System.out.println(key); + } + } + map.clear(); // map 초기화 + } + } + String[] answer = new String[answerList.size()]; + for(int i=0,len=answer.length; i26-idx) return; // 남은 알파벳 수보다 뽑아야 할 알파벳이 더 많으면 종료 + if(n==num) { // num개의 알파벳 다 선택했으면 +// for(int i : arr) { +// System.out.print(i+" "); +// } +// System.out.println(); + int numOfCombo = getNumOfCombo(); + if(numOfCombo>1) { // 해당 코스요리가 둘 이상 존재하면 + StringBuilder sb = new StringBuilder(); + for(int i=0; i0) { + if(usable(tmp)) { // tmp가 가능한 숫자이면 + break; + }else { // tmp가 불가능하면 + tmp++; // 1증가 시켜서 다시 시도 + } + } + min = Math.min(min, tmp-num+String.valueOf(tmp).length()); // tmp 숫자 갯수+tmp까지의 차이를 min값과비교하여 최솟값 갱신 + // num에서 가장 가까운 작은값 찾아서 비교하기 + times = min; // 다시 초기화 + tmp = num; // 다시 초기화 + while(--times>0) { + if(usable(tmp)) { // tmp가 가능한 숫자이면 + break; + }else { // tmp가 불가능하면 + tmp--; // 1감소 시켜서 다시 시도 + if(tmp<0) break; // 0보다 작아지면 불가능하므로 종료 + } + } + if(tmp>=0) { // 0이상이면 최솟값 갱신 + min = Math.min(min, num-tmp+String.valueOf(tmp).length()); // tmp 숫자 갯수+tmp까지의 차이를 min값과비교하여 최솟값 갱신 + } + + System.out.println(min); + } + + public static boolean usable(int num) { + boolean flag = true; + while(true) { + if(broken[num%10]) { // 일의자리 숫자가 사용 불가이면 + flag = false; + break; + }else { + num /= 10; // 한자리 감소 + } + if(num==0) break; // 숫자를 다 확인했으면 종료 + } + return flag; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week25/Baekjoon_2011.java" "b/src/\352\260\225\353\217\231\354\204\235/week25/Baekjoon_2011.java" new file mode 100644 index 0000000..8aa9e70 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week25/Baekjoon_2011.java" @@ -0,0 +1,51 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 암호코드 +/* + * dp[idx] 는 idx번째 까지의 숫자를 고려한 경우의 수이다. + * dp[n]은 조건에 따라 dp[n-1] 과 dp[n-2]를 합한 값이다. + * 기본적으로 dp[n] = dp[n-1]+dp[n-2] 와 비슷한 흐름으로 가지만, 예외인 조건을 잘 찾는것이 이 문제의 핵심인 것 같다. + */ +public class Baekjoon_2011 { + + public static void main(String[] args) throws IOException { + final int MOD = 1000000; + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String str = br.readLine(); + int length = str.length(); // 암호의 길이 + if(length==1) { // 길이가 1이면 + if(str.equals("0")) { // "0"이면 해석불가 + System.out.println(0); + }else { // 그 외에는 1가지 경우의 수 + System.out.println(1); + } + return; + } + String endOfStr = str.substring(length-2); // 마지막 2개의 문자 + if(str.startsWith("0") || // "0"으로 시작하거나 + str.contains("00") || // "00"을 포함하거나 + str.substring(length-1).equals("0") && !(endOfStr.equals("10") || endOfStr.equals("20"))) { // 마지막에 0으로 끝나면서, 10이나 20으로는 끝나지 않을 경우 해석이 불가능하다. + System.out.println(0); + return; + } + int[] dp = new int[length+1]; // dp[idx]: idx번째 문자까지 해석할 수 있는 경우의 수 + dp[0]=1; dp[1]=1; // 0개와 1개까지의 경우의수는 1로 초기화 + + for(int i=2; i<=length; ++i) { + // 마지막 1개의 문자만 고려할 경우 + if(str.charAt(i-1)!='0') { // 새로운 문자가 0이 아니면 + dp[i] += dp[i-1]; // 이전의 경우의수를 그대로 더함 + } + // 마지막 2개의 문자만 고려할 경우 + if(str.charAt(i-2)!='0' && Integer.valueOf(str.substring(i-2,i))<=26) { // 마지막 숫자2개의 십의자리가 0이 아니고 26이하이면 + dp[i] += dp[i-2]; + } + dp[i]%=MOD; // 더한 값이 클 수 있으므로 나누어주기 + } + System.out.println(dp[length]); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_17684.java" "b/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_17684.java" new file mode 100644 index 0000000..0c4c5e0 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_17684.java" @@ -0,0 +1,48 @@ +package programmers; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +// [3차] 압축 +/* + * map을 이용하여 기존에 존재하는 값들을 배열에 저장하고, 새로운 문자열을 발견하면 map에 새로 추가하는 방식으로 + * 어렵지 않게 해결할 수 있다. + */ +public class Programmers_17684 { + + public static void main(String[] args) { + String msg = "ABABABABABABABAB"; + System.out.println(solution(msg)); + } + + public static int[] solution(String msg) { + int length = msg.length(); + Map map = new HashMap(); + ArrayList list = new ArrayList(); + for(char ch='A'; ch<='Z'; ++ch) { + String str = String.valueOf(ch); + map.put(str, ch-'A'+1); // A~Z까지 1~26의 값을 저장 + } + int idx = 27; // Z다음에 저장될 순번 + int from=0,to=0; // msg에서 문자를 가리키는 인덱스 + while(true) { + while(to map = new HashMap(); + for(String[] arr : clothes) { + map.put(arr[1], map.getOrDefault(arr[1], 0)+1); + } + int answer = 1; + for(String key : map.keySet()) { + answer *= map.get(key)+1; + } + return answer-1; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_92343.java" "b/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_92343.java" new file mode 100644 index 0000000..0794fbf --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week25/Programmers_92343.java" @@ -0,0 +1,61 @@ +package programmers; + +import java.util.ArrayList; + +// 양과 늑대 +/* + * info의 길이가 2~17로 이진트리 노드의 갯수가 최대 17개이므로 거의 완전탐색을 하여도 시간걱정을 할 필요가 없는 문제이다. + * dfs를 이용하여 완탐을 하면서, 기존에 갈 수 있는 자식 노드들의 정보를 다음 dfs탐색이 같이 넘겨주면, + * 매 dfs마다 갈 수 있는 자식 노드들의 정보를 가지고 있으면서 완탐을 하게 된다. + */ +public class Programmers_92343 { + + public static void main(String[] args) { + int[] info = {0,0,1,1,1,0,1,0,1,0,1,1}; + int[][] edges = {{0,1},{1,2},{1,4},{0,8},{8,7},{9,10},{9,11},{4,3},{6,5},{4,6},{8,9}}; + System.out.println(solution(info, edges)); + } + + static int max; + static int[] infos; + static ArrayList[] adjList; + + public static int solution(int[] info, int[][] edges) { + infos = info; + int length = info.length; + adjList = new ArrayList[length]; + for(int i=0; i(); + } + for(int[] edge : edges) { + adjList[edge[0]].add(edge[1]); + } + ArrayList start = new ArrayList(); + start.add(0); // 0번 노드만 포함하여 시작 + max=0; + dfs(0,0,0,start); + return max; + } + + public static void dfs(int curNode, int sheep, int wolves, ArrayList childList) { + if(infos[curNode]==0) sheep++; // 해당 노드가 양이면 1마리 증가 + else wolves++; // 아니면 늑대 1마리 증가 + + if(wolves>=sheep) { // 늑대가 양보다 같거나 많으면 종료 + return; + } + if(max nextList = new ArrayList(); + for(int nextNode : adjList[curNode]) { + nextList.add(nextNode); // 현재 노드의 새로운 자식노드들을 추가 + } + for(int nextNode : childList) { // 이전의 갈 수 있는 자식노드들에 대하여 + if(nextNode!=curNode) nextList.add(nextNode); // 현재 노드가 아니면 자식 노드를 전부 합치기 + } + for(int nextNode : nextList) { + dfs(nextNode, sheep, wolves, nextList); // 자식 노드들을 전부 방문 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_15684.java" "b/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_15684.java" new file mode 100644 index 0000000..c097ee4 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_15684.java" @@ -0,0 +1,73 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 사다리 조작 +public class Baekjoon_15684 { + + static int N,M,H; + static int totalNum; + static int answer; + static boolean[][] check; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + M = Integer.parseInt(line[1]); + H = Integer.parseInt(line[2]); + check = new boolean[H][N]; // 오른쪽으로 가로선이 있는 위치에 true + for(int i=0; i0 && check[r][col-1]) col--; // 왼쪽가로선 존재하면 왼쪽 이동 + else if(check[r][col]) col++; // 오른쪽가로선 존재하면 오른쪽 이동 + } + return col; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_2075.java" "b/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_2075.java" new file mode 100644 index 0000000..a0f8552 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week26/Baekjoon_2075.java" @@ -0,0 +1,34 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.PriorityQueue; + +// N번째 큰 수 +/* + * PriorityQueue를 이용하면 기본적으로 오름차순이기때문에, + * 내림차순으로 힙정렬을 한 후 N번째 원소를 출력하면 된다. + * 시간복잡도: O(NlogN) 힙정렬 + */ +public class Baekjoon_2075 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + PriorityQueue pq = new PriorityQueue(Collections.reverseOrder()); + int N = Integer.parseInt(br.readLine()); + String[] line; + for(int i=0; i0) { + pq.poll(); + } + System.out.println(pq.poll()); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_42626.java" "b/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_42626.java" new file mode 100644 index 0000000..8a81f27 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_42626.java" @@ -0,0 +1,41 @@ +package programmers; + +import java.util.PriorityQueue; + +// 더 맵게 +/* + * PriorityQueue를 이용하여 힙정렬을 한 후 최솟값 2개를 계속 계산하여 해결한다. + * 최솟값이 K보다 작으면서 pq에 값이 1개밖에 없으면 -1을 리턴하며 종료한다. + */ +public class Programmers_42626 { + + public static void main(String[] args) { + int[] scoville = {1, 2, 3, 9, 10, 12}; + int K = 150; + System.out.println(solution(scoville, K)); + } + + public static int solution(int[] scoville, int K) { + PriorityQueue pq = new PriorityQueue(); + for(int i=0,len=scoville.length; i10) { // 모든 점수판을 다 확인했는데 화살이 남았으면 + lionArr[10] += arrowLeft; // 남은 화살을 모두 0점에 올인 후 + calcResult(); // 점수 계산 + lionArr[10] = 0; // 점수 계산이 끝난 후에는 마지막 칸의 화살을 초기화 + return; + } + + // 가능하면 현재 점수판을 이기고 다음 점수판으로 이동 + if(apeachArr[idx]apeachArr[i]) { // 라이언이 점수 획득 + gap += 10-i; // 점수만큼 증가 + }else if(apeachArr[i]!=0){ // 어피치의 화살이 존재하면 어피치 점수 획득 + gap -= 10-i; // 점수만큼 감소 + } + } + if(max=0; --i) { + if(answerArr[i]lionArr[i]) { // 기존의 배열이 낮은 점수의 화살이 더 많으면 + break; // 그만 비교 + } + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_92344.java" "b/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_92344.java" new file mode 100644 index 0000000..3d0c89f --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week26/Programmers_92344.java" @@ -0,0 +1,68 @@ +package programmers; + +// 파괴되지 않은 건물 +/* + * 당시 코테에서는 효율성을 해결하지 못했다. + * 하지만 이번에 생각보다 어렵지 않게 누적합 문제라는것을 알 수 있었다. + * 백준에서 비슷한 유형의 문제를 풀어본 것이 도움이 된 것 같다. + * 역시 알고리즘 문제를 꾸준히 풀다보면 실력이 조금이나마 향상된 것 같아 뿌듯하다. + * 풀이법 + * 1. 누적합의 경계설정 + * 2. 가로방향 누적합 계산 and 세로방향 누적합 계산(서로 순서는 바뀌어도 무방) + * 3. 누적합과 원래의 내구도와 비교 + * 시간복잡도: O(K+NM) => skill의 수만큼 경계 설정 4*K + 누적합2번 2*N*M + board와 누적합 전체 비교 N*M = 4K+3NM + */ +public class Programmers_92344 { + + public static void main(String[] args) { + int[][] board = {{5,5,5,5,5},{5,5,5,5,5},{5,5,5,5,5},{5,5,5,5,5}}; + int[][] skill = {{1,0,0,3,4,4},{1,2,0,2,3,2},{2,1,0,3,1,2},{1,0,1,3,3,1}}; + System.out.println(solution(board, skill)); + } + + public static int solution(int[][] board, int[][] skill) { + int R = board.length; // 행의 길이 + int C = board[0].length; // 열의 길이 + int[][] sum = new int[R][C]; // 누적합의 배열 + for(int i=0,len=skill.length; i 오 방향으로 누적합 계산 + for(int r=0; r 아래 방향으로 누적합 계산 + for(int r=1; r0) answer++; + } + } + return answer; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_10026.java" "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_10026.java" new file mode 100644 index 0000000..f829fac --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_10026.java" @@ -0,0 +1,66 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 적록색약 +public class Baekjoon_10026 { + + static int N; + static char[][] map; + static boolean[][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + map = new char[N][N]; + visited = new boolean[N][N]; + String line; + for(int i=0; i=N || nc<0 || nc>=N) continue; // 경계체크 + if(!visited[nr][nc] && map[nr][nc]==ch) dfs(nr,nc,ch); // 방문 및 같은 알파벳 체크 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_1012.java" "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_1012.java" new file mode 100644 index 0000000..1e1ac72 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_1012.java" @@ -0,0 +1,60 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 유기농 배추 +public class Baekjoon_1012 { + + static int N,M,answer; + static int[][] map; + static boolean[][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T = Integer.parseInt(br.readLine()); + StringBuilder sb = new StringBuilder(); + for(int t=0; t=N || nc<0 || nc>=M || visited[nr][nc]) continue; // 경계체크 및 방문체크 + if(map[nr][nc]==1) dfs(nr,nc); // 다음 위치가 배추이면 진행 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_14501.java" "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_14501.java" new file mode 100644 index 0000000..5606152 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_14501.java" @@ -0,0 +1,34 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 퇴사 +public class Baekjoon_14501 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] T = new int[N]; + int[] P = new int[N]; + int[] dp = new int[N]; + String[] line; + for(int i=0; i list = new ArrayList(); + String[] line = br.readLine().split(" "); + for(int i=0; iMath.abs(sum)) { // 최솟값 발견하면 + min=Math.abs(sum); // 최솟값 갱신 + num1=arr[i]; // 숫자 저장 + num2=arr[j]; + num3=arr[k]; + } + if(sum<0) { // 합이 음수이면 숫자의 합이 커져야 하므로 + j++; + }else { // 합이 양수이면 숫자의 합이 작아져야 하므로 + k--; + } + } + } + System.out.println(num1+" "+num2+" "+num3+" "); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_5567.java" "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_5567.java" new file mode 100644 index 0000000..81c5e72 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week27/Baekjoon_5567.java" @@ -0,0 +1,48 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +// 결혼식 +public class Baekjoon_5567 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int m = Integer.parseInt(br.readLine()); + boolean[] visited = new boolean[n+1]; + ArrayList[] adjList = new ArrayList[n+1]; + for(int i=1; i(); + } + String[] line; + for(int i=0; i q = new LinkedList(); + int answer = 0; + visited[1] = true; + for(int num : adjList[1]) { + q.offer(num); + visited[num] = true; + answer++; + } + for(int cur : q) { + for(int next : adjList[cur]) { + if(!visited[next]) { + answer++; + visited[next] = true; + } + } + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week28/Baekjoon_11003.java" "b/src/\352\260\225\353\217\231\354\204\235/week28/Baekjoon_11003.java" new file mode 100644 index 0000000..a10fd54 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week28/Baekjoon_11003.java" @@ -0,0 +1,45 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Deque; +import java.util.LinkedList; + +// 최솟값 찾기 +/* + * 이 문제의 핵심은 매번 새로 들어오는 숫자보다 작은 숫자만 남겨놓으면 된다. + * 가장 최근의 숫자부터 비교해가며 새로운 수보다 작은수가 나올때까지 제거한다. + * 그러면 어차피 큰수들은 필요없으므로 제외되고, 자동적으로 제일 앞에 있는 수가 최솟값이 될것이다. + * 왜냐하면 이전부터 계속 새로운 수보다 작은 수만 남겨놓았으므로. + * 물론 범위밖의 숫자들은 없애주어야 하므로, 이 용도를 위해 숫자와 함께 인덱스도 같이 저장한다. + * 시간복잡도: O(N), 슬라이딩 윈도우 기법 + */ +public class Baekjoon_11003 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + Deque deq = new LinkedList(); // {해당숫자, 인덱스} 저장 + StringBuilder sb = new StringBuilder(); + String[] line = br.readLine().split(" "); + int N = Integer.parseInt(line[0]); + int L = Integer.parseInt(line[1]); + int[] arr = new int[N+1]; + line = br.readLine().split(" "); + for(int i=0; inextNum) { // 새로운수보다 마지막 수가 크면 + deq.pollLast(); // 큰 수들 다 제거 + } + deq.offer(new int[] {nextNum,i}); // 새로운 수와 인덱스 추가 + if(deq.peekFirst()[1][] adjlist; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + chosen = new boolean[N]; + adjlist = new ArrayList[N]; + for(int i=0; i(); + } + String[] line; + for(int i=1; i cloudPos = new ArrayList(); + static int[][] dir = {{0,0},{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1}}; + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + M = Integer.parseInt(line[1]); + map = new int[N][N]; + existed = new boolean[N][N]; + for(int i=0; i0 && c>0 && map[r-1][c-1]!=0) map[r][c]++; + if(r>0 && c0 && map[r+1][c-1]!=0) map[r][c]++; + if(r1) { // 2이상이면 + map[i][j] -= 2; + cloudPos.add(new int[] {i,j}); + } + } + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_1654.java" "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_1654.java" new file mode 100644 index 0000000..52338ac --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_1654.java" @@ -0,0 +1,43 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 랜선 자르기 +/* + * 이분탐색 시 범위조절과 등호 여부를 잘 판단해야할 것 같다. + */ +public class Baekjoon_1654 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + int K = Integer.parseInt(str[0]); + int N = Integer.parseInt(str[1]); + long[] len = new long[K]; + long maxLen = 0; // 최장 랜선의 길이 + long answer = 0; + for(int i=0; i=N) { + answer=mid; // 결과 최댓값 갱신 + low = mid+1; // 길이 증가 + }else { + high = mid-1; // 길이 감소 + } + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_20056.java" "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_20056.java" new file mode 100644 index 0000000..3d6211c --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_20056.java" @@ -0,0 +1,128 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 마법사 상어와 파이어볼 +/* + * 질량,속도,방향을 합쳐서 저장하는 방법을 잘 구현해야 풀 수 있는 문제였다. + */ +public class Baekjoon_20056 { + + static class FireBall { + int r,c,m,s,d; + + public FireBall(int r, int c, int m, int s, int d) { + super(); + this.r = r; + this.c = c; + this.m = m; + this.s = s; + this.d = d; + } + + } + + static int N,M,K; + static FireBall[][] map; + static int[][] count; + static ArrayList list; + static int[][] dir = {{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + K = Integer.parseInt(str[2]); + map = new FireBall[N][N]; + count = new int[N][N]; + list = new ArrayList(); + for(int i=0; i=0) { // 방향이 통일되어 있으면 + if((cur.d + fb.d)%2 != 0) { // 홀이나 짝이 다르면 + cur.d = -1; // 방향을 음수로 처리 + } + } + } + count[nr][nc] += 1; + } + } + + public static void split() { + list.clear(); + for(int i=0; i1) { // 파이어볼 2개 이상겹치면 + FireBall fb = map[i][j]; + int r = fb.r; + int c = fb.c; + int m = fb.m/5; + if(m>0) { // 질량이 0이 아니면 + int s = fb.s/cnt; + int d = fb.d; + if(d>=0) { // 방향이 모두 같으면 0,2,4,6 + list.add(new FireBall(r, c, m, s, 0)); + list.add(new FireBall(r, c, m, s, 2)); + list.add(new FireBall(r, c, m, s, 4)); + list.add(new FireBall(r, c, m, s, 6)); + }else { // 방향이 다르면 1,3,5,7 + list.add(new FireBall(r, c, m, s, 1)); + list.add(new FireBall(r, c, m, s, 3)); + list.add(new FireBall(r, c, m, s, 5)); + list.add(new FireBall(r, c, m, s, 7)); + } + } + } + // 빈칸으로 초기화 + map[i][j] = null; + count[i][j]=0; + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_2206.java" "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_2206.java" new file mode 100644 index 0000000..ea8c1eb --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week29/Baekjoon_2206.java" @@ -0,0 +1,69 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; + +// 벽 부수고 이동하기 +/* + * 벽을 부쉈는지 아닌지를 체크하면서 동시에 방문체크를 하기 위해 + * 3차원 boolean배열 3번째 인덱스를 벽을 부순 횟수의 상태를 체크하는데 사용한다. + */ +public class Baekjoon_2206 { + + static char[][] map; + static boolean[][][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + int N = Integer.parseInt(str[0]); + int M = Integer.parseInt(str[1]); + map = new char[N][M]; + visited = new boolean[N][M][2]; + for(int i=0; i q = new LinkedList(); + q.offer(new int[] {0,0,0}); + + int answer = -1; + int depth = 0; + while(!q.isEmpty()) { + int size = q.size(); + depth++; // 이동거리 + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + int state = cur[2]; + if(visited[r][c][state]) continue; // 이미 방문했으면 + visited[r][c][state] = true; // 방문처리 + + if(r==N-1 && c==M-1) { // 마지막칸에 도착했으면 + answer = depth; // 이동거리 저장 + break; + } + + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=N || nc<0 || nc>=M) continue; // 경계체크 + if(map[nr][nc]=='0') { // 다음칸이 벽 없으면 + if(visited[nr][nc][0]) continue; // 방문체크 + q.offer(new int[] {nr,nc,state}); + }else if(map[nr][nc]=='1' && state==0) { // 다음칸 벽이고 이전에 벽 안부쉈으면 + if(visited[nr][nc][1]) continue; // 방문체크 + q.offer(new int[] {nr,nc,1}); // 상태를 벽 부순걸로 바꿈 + } + } + } + if(answer>0) break; // 최단거리 저장했으면 종료 + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week29/Programmers_12920.java" "b/src/\352\260\225\353\217\231\354\204\235/week29/Programmers_12920.java" new file mode 100644 index 0000000..6240d4f --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week29/Programmers_12920.java" @@ -0,0 +1,52 @@ +package programmers; + +// 선입 선출 스케줄링 +/* + * 특정 시각까지 몇개의 작업을 받아들였는지를 이분탐색을 통하여 계산한 후 + * n개 직전까지의 시각과 작업갯수를 구하여 그 다음시각에 몇번째 코어에 할당되는지를 계산한다. + */ +public class Programmers_12920 { + + public static void main(String[] args) { + int n = 7; + int[] cores = {50,50,50,30}; + System.out.println(solution(n, cores)); + } + + public static int solution(int n, int[] cores) { + int len = cores.length; + + int beforeStart = 0; + int sum = 0; + + int low = 1; + int high = 10000*50000/2; // 코어는최소 시간은 최대일 때 + while(low=n) { + high = mid-1; + }else { + beforeStart = mid; // 시간 저장 + sum = cnt; // 처리한 작업 수 저장 + low = mid+1; + } + } + + int answer = 0; + for(int i=0; iN-num) { // 뽑아야 하는 수 > 남은 선수 수 + return; + } + + for(int i=num; i[][] treeAges; // 나무들의 나이를 저장 + static int[][] A; + static int[][] dir = {{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + M = Integer.parseInt(line[1]); + K = Integer.parseInt(line[2]); + nutrition = new int[N+1][N+1]; + for(int i=1; i<=N; ++i) { + for(int j=1; j<=N; ++j) { + nutrition[i][j] = 5; // 양분 초기화 + } + } + + A = new int[N+1][N+1]; // 매년 추가할 양분 + for(int i=1; i<=N; ++i) { + line = br.readLine().split(" "); + for(int j=1; j<=N; ++j) { + A[i][j] = Integer.parseInt(line[j-1]); + } + } + + treeAges = new PriorityQueue[N+2][N+2]; // 바깥쪽 패딩 + for(int i=0; i(); + } + } + + // 처음에 나무 심기 + for(int i=0; i nextAges = new PriorityQueue(); + int deadSum = 0; // 죽어서 영양분이 될 나무 + while(!treeAges[i][j].isEmpty()) { + int age = treeAges[i][j].poll(); // 가장 어린 나무 선택 + if(nutrition[i][j]>=age) { // 영양분 충분하면 + nutrition[i][j] -= age; // 나이만큼 감소 + nextAges.offer(age+1); // 1살 증가한 나무 나이 추가 + }else { + deadSum += age/2; // 죽은 나무 나이의 절반만큼 영양분 증가 + } + } + treeAges[i][j] = nextAges; + nutrition[i][j] += deadSum; // 죽은 나무 영양분만큼 증가 + } + } + } + + public static void fall() { + for(int i=1; i<=N; ++i) { + for(int j=1; j<=N; ++j) { + int cnt = 0; // 번식할 나무의 갯수 + for(int age : treeAges[i][j]) { + if(age%5==0) { // 나무의 나이가 5의 배수이면 + cnt++; // 갯수 증가 + } + } + for(int d=0; d<8; ++d) { + int nr = i+dir[d][0]; + int nc = j+dir[d][1]; + for(int c=0; c posSet; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + posSet = new HashSet(); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + map = new char[N][M]; + answer = new int[N][M]; + visited = new boolean[N][M]; + for(int i=0; i=N || nc<0 || nc>=M || visited[nr][nc]) continue; // 경계 및 방문체크 + if(map[nr][nc]=='1') { // 벽이면 + posSet.add(nr*M+nc); + }else { // 벽이 아니면 + dfs(nr,nc); + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week30/Baekjoon_4991.java" "b/src/\352\260\225\353\217\231\354\204\235/week30/Baekjoon_4991.java" new file mode 100644 index 0000000..e368fe9 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week30/Baekjoon_4991.java" @@ -0,0 +1,127 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +// 로봇 청소기 +/* + * bfs로 로봇과 모든 더러운 칸들사이의 거리를 계산하여 2차연 배열로 저장한 후 + * next permutation을 오랜만에 사용하여 순열을 만든 후 + * 순서에따라 청소하며 최솟값을 갱신하였다. + */ +public class Baekjoon_4991 { + + static int R,C; + static int[][] dist; + static char[][] map; + static ArrayList pos; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + loop:while(true) { + String[] line = br.readLine().split(" "); + R = Integer.parseInt(line[1]); + C = Integer.parseInt(line[0]); + if(R==0) break; + map = new char[R][C]; + for(int i=0; i(); + int cnt = 0; // 더러운 칸의 수 + for(int r=0; rsum) answer=sum; // 최솟값 갱신 + }while(np(orders)); + sb.append(answer).append("\n"); + } + System.out.println(sb.toString()); + } + + public static int calcDistance(int[] from, int[] to) { + int dist = 0; // from부터 to까지의 거리 + boolean[][] visited = new boolean[R][C]; + Queue q = new LinkedList(); + q.offer(from); + while(!q.isEmpty()) { + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(visited[r][c]) continue; + if(r==to[0] && c==to[1]) { // 도착지 + return dist; + } + visited[r][c] = true; + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=R || nc<0 || nc>=C || visited[nr][nc]) continue; + if(map[nr][nc]!='x') q.offer(new int[] {nr,nc}); // 벽이 아니면 큐에 삽입 + } + } + dist++; + } + return -1; // 경로가 없으면 -1 + } + + public static boolean np(int[] numbers) { + int N = numbers.length; + int i = N-1; + while(i>0 && numbers[i-1]>=numbers[i]) i--; + if(i==0) return false; + + int j = N-1; + while(numbers[i-1]>=numbers[j]) j--; + swap(numbers,i-1,j); + + int k = N-1; + while(i4 || nc<0 || nc>4) continue; // 경계 + if(map[nr][nc]=='P') { + return false; + } + } + for(int d=0; d<8; d+=2) { // 상하좌우 2칸 + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>4 || nc<0 || nc>4) continue; // 경계 + if(map[nr][nc]=='O') { // 옆칸이 O면 + nr += dir[d][0]; // 한칸더 전진 + nc += dir[d][1]; + if(nr<0 || nr>4 || nc<0 || nc>4) continue; // 경계 + if(map[nr][nc]=='P') { + return false; + } + } + } + for(int d=1; d<8; d+=2) { // 대각선 1칸 + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>4 || nc<0 || nc>4) continue; // 경계 + if(map[nr][nc]=='P') { // 대각선이 P이면 + if(map[r][nc]=='O' || map[nr][c]=='O') { // 둘 사이에 하나라도 O가 있으면 + return false; + } + } + } + return true; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_1007.java" "b/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_1007.java" new file mode 100644 index 0000000..fde01d8 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_1007.java" @@ -0,0 +1,57 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 벡터 매칭 +/* + * 구글링을 참고하였다. + * N/2개의 벡터의 합을 구하는 것은 + * N/2개의 점의 좌표의 합과 나머지 N/2개의 점의 좌표의 합 차이를 구하는것이므로 + * N/2개의 점을 선택한 후 전체합과 비교하여 쉽게 차이를 구할 수 있다. 그 중 최솟값을 찾으면 된다. + */ +public class Baekjoon_1007 { + + static int N; + static double answer; + static int[] posSum; + static ArrayList list; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T = Integer.parseInt(br.readLine()); + for(int t=0; t(); + N = Integer.parseInt(br.readLine()); + posSum = new int[2]; + answer = Double.MAX_VALUE; + for(int i=0; iN/2) return; // 가지치기 + if(n==N/2) { + long r = Math.abs(2*sum[0]-posSum[0]); + long c = Math.abs(2*sum[1]-posSum[1]); + answer = Math.min(answer, Math.sqrt(r*r+c*c)); + return; + } + for(int i=idx; i=0; --r) { + int min = Integer.MAX_VALUE; + for(int idx=c; idx>r; --idx) { + min = Math.min(min, dp[r][idx-1]+dp[idx][c]+arr[r][0]*arr[idx][0]*arr[c][1]); + } + dp[r][c] = min; + } + } + System.out.println(dp[0][N-1]); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_14888.java" "b/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_14888.java" new file mode 100644 index 0000000..e626bb1 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week31/Baekjoon_14888.java" @@ -0,0 +1,71 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 연산자 끼워넣기 +/* + * 중복조합 문제이다. + * 무난하게 브루트포스로 가능한 모든 연산자의 경우를 고려하여 최대,최소값을 구하면 된다. + */ +public class Baekjoon_14888 { + + static int N,min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; + static int[] A; + static int[] op; // 연산자 순서 + static int[] opCnt = new int[4]; // 연산자 갯수 + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + A = new int[N]; + op = new int[N-1]; + String[] line = br.readLine().split(" "); + for(int i=0; i0) { + opCnt[i]--; + op[n]=i; + dfs(n+1); + opCnt[i]++; + } + + } + } + + public static void calcResult() { + int result = A[0]; + for(int i=0; iresult) min = result; + if(max direction = new ArrayList(); + direction.add(0); + for(int cnt=0; cnt<10; ++cnt) { + for(int i=direction.size()-1; i>=0; --i) { + direction.add((direction.get(i)+1)%4); + } + } + boolean[][] check = new boolean[101][101]; + int N = Integer.parseInt(br.readLine()); + int[][] map = new int[101][101]; + for(int i=0; i list = new ArrayList(); + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + for(int i=0; i<9; ++i) { + String[] line = br.readLine().split(" "); + for(int j=0; j<9; ++j) { + int n = Integer.parseInt(line[j]); + map[i][j] = n; + if(n==0) { + list.add(new int[] {i,j}); + N++; // 0의 갯수 증가 + } + } + } + dfs(0); + StringBuilder sb = new StringBuilder(); + for(int i=0; i<9; ++i) { + for(int j=0; j<9; ++j) { + sb.append(map[i][j]).append(" "); + } + sb.append("\n"); + } + System.out.println(sb.toString()); + } + + public static boolean dfs(int n) { + if(n==N) { // 정답 찾으면 true 리턴 + return true; + } + + int[] cur = list.get(n); + int r = cur[0]; + int c = cur[1]; + for(int i=1; i<=9; ++i) { + if(check(r,c,i)) { // r,c에 숫자i가 가능하면 + map[r][c]=i; // i 대입 + if(dfs(n+1)) return true; // 정답 찾으면 true리턴 + map[r][c]=0; // i 취소 + } + } + + return false; + } + + public static boolean check(int r, int c, int num) { + for(int i=0; i<9; ++i) { + if(map[r][i]==num) return false; + } + for(int i=0; i<9; ++i) { + if(map[i][c]==num) return false; + } + int R = r/3; + int C = c/3; + for(int i=R*3; i q = new LinkedList(); + q.offer(new int[] {sharkR,sharkC}); // 현재 상어의 위치 + visited[sharkR][sharkC] = true; // 현재 상어위치 방문처리 + + int targetR = Integer.MAX_VALUE; // 목표 물고기의 행 + int targetC = Integer.MAX_VALUE; // 목표 물고기의 열 + + int depth = 0; + int distance = 0; // 이동거리 + while(!q.isEmpty()) { + int size = q.size(); + while(--size>=0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(map[r][c] != 0 && map[r][c]0) { // 먹을 수 있는 물고기를 발견하면 + result += distance; // 최종 이동거리 증가 + return new int[] {targetR,targetC}; // 탐색 종료 + } + } + return null; // 물고기 발견 못하면 null 리턴 + } + public static void eatFish(int[] target) { + map[sharkR][sharkC]=0; // 기존의 상어 위치를 0으로 변경 + // 상어를 물고기 위치로 이동 + sharkR = target[0]; + sharkC = target[1]; + map[sharkR][sharkC]=0; // 상어의 위치를 0으로 표시 + eatenFishCnt++; // 먹은 물고기수 증가 + + } + public static void levelUpCheck() { // 상어 크기 증가 확인 + if(eatenFishCnt==sharkLevel) { + sharkLevel++; // 상어 크기 증가 + eatenFishCnt = 0; // 0으로 초기화 + } + } + public static void visitedReset() { // false로 초기화 + for(int i=0; i=0 && r=0 && c pos; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상,우,하,좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + map = new int[N][N]; + comb = new int[M]; + pos = new ArrayList(); + for(int i=0; i q = new LinkedList(); + boolean[][] visited = new boolean[N][N]; + for(int idx : comb) { + int[] cur = pos.get(idx); + q.add(cur); + } + int dist = -1; + int cnt = 0; // 0을 채우는 갯수 + while(!q.isEmpty()) { + dist++; // 거리증가 + if(dist>=answer) break; // 가지치기, 기존보다 더 멀리가면 더 이상 비교 X + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(visited[r][c]) continue; + visited[r][c] = true; + if(map[r][c]==0) cnt++; // 빈칸이면 갯수 증가 + if(cnt==emptyCnt) { + answer = dist; + return; // 빈칸 다 채우면 종료 + } + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=N || nc<0 || nc>=N || visited[nr][nc]) continue; // 경계 및 방문체크 + if(map[nr][nc]!=1) { // 다음칸이 벽이 아니면 + q.offer(new int[] {nr,nc}); + } + } + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_19238.java" "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_19238.java" new file mode 100644 index 0000000..ab58fe4 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_19238.java" @@ -0,0 +1,154 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; + +// 스타트 택시 +/* + * BFS이용한 단순 시뮬문제지만 예외케이스를 잘 처리해야한다. + * 1. 손님을 태우는 길이 막힌 경우 + * 2. 손님을 태웠지만 목적지에 가는 길이 막힌 경우 + * 3. 손님이 내리자마자 다른 손님이 타는 경우 + */ +public class Baekjoon_19238 { + + static int N,M,fuel; + static int carR,carC; + static int[][] map; + static int[][] dest; // 목적지 + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상우하좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + fuel = Integer.parseInt(str[2]); + map = new int[N+2][N+2]; // 바깥 패딩 + for(int r=0; r q = new LinkedList(); + q.offer(new int[] {carR,carC}); + int dist = 0; + while(!q.isEmpty()) { + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(visited[r][c]) continue; + visited[r][c] = true; + if(map[r][c]>1) { // 해당칸에 사람이 있으면 + if(r q = new LinkedList(); + q.offer(new int[] {carR,carC}); + int dist = 0; + while(!q.isEmpty()) { + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + if(visited[r][c]) continue; + visited[r][c] = true; + if(r==dest[personNum][0] && c==dest[personNum][1]) { // 목적지에 도착했으면 + carR = r; // 차 위치 이동 + carC = c; + fuel -= dist; // 연료 소모 + return dist; + } + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(!visited[nr][nc] && map[nr][nc]!=1) { // 방문 체크,벽체크 + q.offer(new int[] {nr,nc}); + } + } + } // end while + dist++; // 거리 증가 + } // end while + return -1; // -1을 반환하면 목적지까지 이동 불가 + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_1938.java" "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_1938.java" new file mode 100644 index 0000000..87002c2 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_1938.java" @@ -0,0 +1,110 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; + +// 통나무 옮기기 +/* + * 상태를 가로,세로 2가지로 나눠서 구분하여 bfs를 실행하면 된다. + */ +public class Baekjoon_1938 { + + static int N; + static int startR,startC,startS; // 시작의 행,열,상태(0:가로, 1:세로) + static int endR,endC,endS; // 도착 + static char[][] map; + static boolean[][][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1},{-1,-1},{-1,1},{1,1},{1,-1}}; // 상,우,하,좌,대각선4방향 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + map = new char[N][N]; + visited = new boolean[N][N][2]; // [행][열][상태(0또는1)] + for(int i=0; i q = new LinkedList(); + q.offer(new int[] {startR,startC,startS}); + int depth = 0; + while(!q.isEmpty()) { + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + int s = cur[2]; + + if(visited[r][c][s]) continue; + visited[r][c][s] = true; + if(r==endR && c==endC && s==endS) { + System.out.println(depth); + return; + } + // 4방탐색 + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(s==0) { // 가로이면 + if(nr<0 || nr>=N || nc<=0 || nc>=N-1 || map[nr][nc]=='1' || visited[nr][nc][s]) continue; // 경계 및 방문 체크 + }else { // 세로이면 + if(nr<=0 || nr>=N-1 || nc<0 || nc>=N || map[nr][nc]=='1' || visited[nr][nc][s]) continue; // 경계 및 방문 체크 + } + if(canMove(nr,nc,s)) q.offer(new int[] {nr,nc,s}); + } + boolean canRotate = true; // 회전가능 여부 + for(int d=0; d<8; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=N || nc<0 || nc>=N || map[nr][nc]=='1') { + canRotate = false; + break; + } + } + // 회전 + if(canRotate && !visited[r][c][s^1]) { // 회전가능 및 미방문 + q.offer(new int[] {r,c,s^1}); // 제자리 회전 + } + } + depth++; + } + System.out.println(0); + } + + public static boolean canMove(int r, int c, int s) { + if(s==0) { + if(map[r][c-1]=='1' || map[r][c+1]=='1') return false; + }else { + if(map[r-1][c]=='1' || map[r+1][c]=='1') return false; + } + return true; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_20061.java" "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_20061.java" new file mode 100644 index 0000000..fb84c2e --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week32/Baekjoon_20061.java" @@ -0,0 +1,211 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 모노미노도미노 2 +/* + * 문제에서 시키는대로만 배열을 잘 이동시키면 된다. + * 깔끔해도 이동해보려고 한줄을 통째로 묶는 과정에서 ArrayList을 사용했다가 괜히 얕은복사 때문에 디버깅에 고생만했다. + * 차라리 처음부터 boolean[][]로 선언할 걸 그랬다. + * 다른분 풀이를 보니 비트연산자로 해결하신 분도 있었다ㄷㄷ + */ +public class Baekjoon_20061 { + + static int sum,leftCnt; + static ArrayList[] blue,green; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + blue = new ArrayList[6]; + green = new ArrayList[6]; + for(int i=0; i<6; ++i) { + blue[i] = new ArrayList(); + blue[i].add(new boolean[] {false,false,false,false}); + green[i] = new ArrayList(); + green[i].add(new boolean[] {false,false,false,false}); + } + int N = Integer.parseInt(br.readLine()); + for(int i=0; i0; --j) { + blue[j].clear(); + blue[j].add(blue[j-1].get(0)); +// blue[j]=blue[j-1]; // 그 줄을 지우고 한칸씩 이동 + } + blue[0] = new ArrayList(); + blue[0].add(new boolean[] {false,false,false,false}); // 제일 앞에 새로운줄 생성 + sum++; // 점수 증가 + } + // 초록줄 제거 + cur = green[i].get(0); + if(cur[0] && cur[1] && cur[2] && cur[3]) { // 꽉찬 줄이 있으면 + for(int j=i; j>0; --j) { + green[j].clear(); + green[j].add(green[j-1].get(0)); + } + green[0] = new ArrayList(); + green[0].add(new boolean[] {false,false,false,false}); // 제일 앞에 새로운줄 생성 + sum++; // 점수 증가 + } + } + } + + public static void removeSpecialLine() { // 연한 줄 제거 + int blueCnt = 0; + int greenCnt = 0; + for(int i=0; i<2; ++i) { + boolean[] cur = blue[i].get(0); + if(cur[0] || cur[1] || cur[2] || cur[3]) { // 블럭이 하나라도 있으면 + blueCnt++; // 파랑줄 카운트 + } + cur = green[i].get(0); + if(cur[0] || cur[1] || cur[2] || cur[3]) { // 블럭이 하나라도 있으면 + greenCnt++; // 초록줄 카운트 + } + } + if(blueCnt>0) { // 옮길 줄이 있으면 + for(int i=5; i>=blueCnt; --i) { + blue[i].clear(); + blue[i].add(blue[i-blueCnt].get(0)); + } + for(int i=blueCnt-1; i>=0; --i) { + blue[i].clear(); // 줄 정보 삭제 + blue[i].add(new boolean[] {false,false,false,false}); // 쥴 초기화 + } + } + if(greenCnt>0) { // 옮길 줄이 있으면 + for(int i=5; i>=greenCnt; --i) { + green[i].clear(); + green[i].add(green[i-greenCnt].get(0)); + } + for(int i=greenCnt-1; i>=0; --i) { + green[i].clear(); // 줄 정보 삭제 + green[i].add(new boolean[] {false,false,false,false}); // 쥴 초기화 + } + } + } +// public static void print() { +// for(int i=0; i<4; ++i) { +// for(int j=0; j<6; ++j) { +// if(blue[j].get(0)[i]) { +// System.out.print(1+" "); +// }else { +// System.out.print(0+" "); +// } +// } +// System.out.println(); +// } +// System.out.println(); +// for(int j=0; j<6; ++j) { +// for(boolean a : green[j].get(0)) { +// if(a) { +// System.out.print(1+" "); +// }else { +// System.out.print(0+" "); +// } +// } +// System.out.println(); +// } +// } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14499.java" "b/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14499.java" new file mode 100644 index 0000000..63168ff --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14499.java" @@ -0,0 +1,69 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 주사위 굴리기 +/* + * 윗면, 북쪽면, 오른쪽면을 항상 기억하고, 맞은편의 두 수의 합이 7인것을 이용하여 반대편을 구할 수 있다. + * 주사위를 움직일 때 마다 바뀌는 면을 새로 갱신하고, 규칙에 따라서 지도 혹은 주사위의 숫자를 변경한다. + */ +public class Baekjoon_14499 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int[] dice = new int[7]; + int N,M,x,y,k; + int up=1,north=2,east=3; + String[] line = br.readLine().split(" "); + N = Integer.parseInt(line[0]); + M = Integer.parseInt(line[1]); + x = Integer.parseInt(line[2]); + y = Integer.parseInt(line[3]); + k = Integer.parseInt(line[4]); + + int[][] map = new int[N][M]; + for(int i=0; i=M-1) continue; + y++; + int west = 7-east; // 동쪽의 반대편인 서쪽 + east = up; + up = west; + }else if(d==2) { // 서 + if(y<=0) continue; + y--; + int down = 7-up; // 위쪽의 반대편인 아래쪽 + up = east; + east = down; + }else if(d==3) { // 북 + if(x<=0) continue; + x--; + int south = 7-north; // 북쪽의 반대편인 남쪽 + north = up; + up = south; + }else { // 남 + if(x>=N-1) continue; + x++; + int down = 7-up; // 위쪽의 반대편인 아래쪽 + up = north; + north = down; + } + if(map[x][y]==0) map[x][y]=dice[7-up]; // 지도에 0이면 아랫면의 숫자를 바닥에 저장 + else { // 지도에 0이 아니면 그 숫자를 주사위 아랫면에 저장 후 지도는 0으로 표시 + dice[7-up]=map[x][y]; + map[x][y]=0; + } + System.out.println(dice[up]); // 위쪽면에 저장된 숫자를 출력 + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14888.java" "b/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14888.java" new file mode 100644 index 0000000..e626bb1 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week33/Baekjoon_14888.java" @@ -0,0 +1,71 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 연산자 끼워넣기 +/* + * 중복조합 문제이다. + * 무난하게 브루트포스로 가능한 모든 연산자의 경우를 고려하여 최대,최소값을 구하면 된다. + */ +public class Baekjoon_14888 { + + static int N,min=Integer.MAX_VALUE,max=Integer.MIN_VALUE; + static int[] A; + static int[] op; // 연산자 순서 + static int[] opCnt = new int[4]; // 연산자 갯수 + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + A = new int[N]; + op = new int[N-1]; + String[] line = br.readLine().split(" "); + for(int i=0; i0) { + opCnt[i]--; + op[n]=i; + dfs(n+1); + opCnt[i]++; + } + + } + } + + public static void calcResult() { + int result = A[0]; + for(int i=0; iresult) min = result; + if(max pq; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + map = new int[100][100]; + String[] str = br.readLine().split(" "); + int r = Integer.parseInt(str[0]); + int c = Integer.parseInt(str[1]); + int k = Integer.parseInt(str[2]); + for(int i=0; i<3; ++i) { + str = br.readLine().split(" "); + for(int j=0; j<3; ++j) { + map[i][j] = Integer.parseInt(str[j]); + } + } + + pq = new PriorityQueue(new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if(o1[1]==o2[1]) { + return Integer.compare(o1[0], o2[0]); + }else { + return Integer.compare(o1[1], o2[1]); + } + } + }); + + R=3; C=3; + int t = -1; + while(t++<=100) { + if(map[r-1][c-1]==k) { + System.out.println(t); + return; + } + if(R>=C) { // R연산 + calcR(); + }else { // C연산 + calcC(); + } + } + System.out.println(-1); + } + + public static void calcR() { + C=0; + for(int r=0; r hashMap = new HashMap(); + for(int c=0; c<100; ++c) { + if(map[r][c]==0) continue; // 0이면 무시 + hashMap.put(map[r][c], hashMap.getOrDefault(map[r][c], 0)+1); + } + for(int key : hashMap.keySet()) { + pq.offer(new int[] {key,hashMap.get(key)}); + } + for(int c=0; c<100; c+=2) { + if(!pq.isEmpty()) { + int[] cur = pq.poll(); + map[r][c] = cur[0]; + map[r][c+1] = cur[1]; + C=Math.max(C, c+2); + }else { + map[r][c] = 0; + map[r][c+1] = 0; + } + } + } + } + public static void calcC() { + R=0; + for(int c=0; c hashMap = new HashMap(); + for(int r=0; r<100; ++r) { + if(map[r][c]==0) continue; // 0이면 무시 + hashMap.put(map[r][c], hashMap.getOrDefault(map[r][c], 0)+1); + } + for(int key : hashMap.keySet()) { + pq.offer(new int[] {key,hashMap.get(key)}); + } + for(int r=0; r<100; r+=2) { + if(!pq.isEmpty()) { + int[] cur = pq.poll(); + map[r][c] = cur[0]; + map[r+1][c] = cur[1]; + R=Math.max(R, r+2); + }else { + map[r][c] = 0; + map[r+1][c] = 0; + } + } + } + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_10942.java" "b/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_10942.java" new file mode 100644 index 0000000..f62fe9a --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_10942.java" @@ -0,0 +1,42 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 팰린드롬? +public class Baekjoon_10942 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + String[] str = br.readLine().split(" "); + int[] nums = new int[N+1]; + boolean[][] dp = new boolean[N+1][N+1]; + for(int i=1; i<=N; ++i) { + nums[i] = Integer.parseInt(str[i-1]); + } + + for(int i=1; i0; --i) { + for(int j=i+2; j<=N; ++j) { + if(dp[i+1][j-1] && nums[i]==nums[j]) dp[i][j] = true; + } + } + int M = Integer.parseInt(br.readLine()); + StringBuilder sb = new StringBuilder(); + for(int i=0; i cntMap; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; // 상우하좌 + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + map = new int[M][N]; + path = new boolean[M][N][4]; + cntMap = new HashMap(); + for(int i=0; i=M || nj<0 || nj>=N) continue; // 경계체크 + if(map[i][j]!=map[ni][nj]) { // 서로 다른 구역이면 + int total = cntMap.get(map[i][j])+cntMap.get(map[ni][nj]); + unionMax = Math.max(unionMax, total); + } + } + } + } + System.out.println(cnt); + System.out.println(max); + System.out.println(unionMax); + } + + public static void bfs(int i, int j, int cnt) { + Queue q = new LinkedList(); + q.offer(new int[] {i,j}); + boolean[][] visited = new boolean[M][N]; + ArrayList list = new ArrayList(); + int num = 0; // 칸의 갯수 + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if(visited[r][c]) continue; + visited[r][c] = true; + list.add(new int[] {r,c}); + num++; + + for(int d=0; d<4; ++d) { + if(!path[r][c][d]) continue; // 길이 없으면 무시 + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=M || nc<0 || nc>=N || visited[nr][nc]) continue; + q.offer(new int[] {nr,nc}); + } + } + for(int[] cur : list) { + map[cur[0]][cur[1]] = cnt; + } + cntMap.put(cnt, num); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_3085.java" "b/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_3085.java" new file mode 100644 index 0000000..2b31b1f --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week34/Baekjoon_3085.java" @@ -0,0 +1,70 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 사탕 게임 +public class Baekjoon_3085 { + + static int N,ans; + static char[][] map; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + N = Integer.parseInt(br.readLine()); + map = new char[N][N]; + for(int i=0; i=0; i--) { // 왼쪽 + if(map[r][i]==color) row++; + else break; + } + for(int i=c+1; i=0; i--) { // 위쪽 + if(map[i][c]==color) col++; + else break; + } + for(int i=r+1; imove) { + move = n; + } + + for(int r=0; r<5; ++r) { + for(int c=0; c<9; ++c) { + if(map[r][c]=='o') { + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(!isValid(nr, nc) || map[nr][nc]!='o') continue; // 경계 및 핀 체크 + + int nnr = nr+dir[d][0]; + int nnc = nc+dir[d][1]; + if(!isValid(nnr, nnc) || map[nnr][nnc]!='.') continue; // 경계 및 빈칸 체크 + + map[r][c]=map[nr][nc]='.'; // 변경 + map[nnr][nnc]='o'; // 변경 + dfs(n+1); + map[r][c]=map[nr][nc]='o'; // 복구 + map[nnr][nnc]='.'; // 복구 + } + } + } + } + + } + + public static boolean isValid(int r, int c) { + return r>=0 && r<5 && c>=0 && c<9; + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1655.java" "b/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1655.java" new file mode 100644 index 0000000..1cce95d --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1655.java" @@ -0,0 +1,45 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; + +// 가운데를 말해요 +/* + * 이분탐색을 통해 새로운 숫자가 어디에 위치할지 빠르게 찾은 후 + * 계속해서 중간값을 출력하면 된다. + */ +public class Baekjoon_1655 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + int N = Integer.parseInt(br.readLine()); + ArrayList list = new ArrayList(); + list.add(Integer.parseInt(br.readLine())); // 1개는 넣기 + sb.append(list.get(0)).append("\n"); // 1개만 있을 때 숫자 말하기 + for(int i=1; in) { + high = mid-1; + }else if(list.get(mid)=n) { // 새로운 수가 mid보다 같거나 작으면 + list.add(mid,n); // 그자리에 집어넣기 + }else { // mid보다 크면 + list.add(mid+1,n); // 한 칸 다음에 집어넣기 + } + sb.append(list.get((i)/2)).append("\n"); + } + System.out.println(sb.toString()); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1912.java" "b/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1912.java" new file mode 100644 index 0000000..7750bb5 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week35/Baekjoon_1912.java" @@ -0,0 +1,44 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 연속합 +/* + * dp[2][N] + * 0행은 누적합, 1행은 누적합 중 최솟값 + * dp[0][i] - dp[1][i]의 최댓값을 구하면 된다. + */ +public class Baekjoon_1912 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + int max = Integer.MIN_VALUE; + String[] str = br.readLine().split(" "); + for(int i=0; i 0) { // 전부 양수 + System.out.println(arr[0]+" "+arr[1]); + return; + }else if(arr[N-1]<0) { // 전부 음수 + System.out.println(arr[N-2]+" "+arr[N-1]); + return; + } + int n1=0,n2=0; // 비교 숫자 + int ans1=0,ans2=0; // 답인 숫자 + int min = Integer.MAX_VALUE; + for(int i=0; iMath.abs(sum)) { // 같은 수를 선택하지 않고, 절댓값이 작으면 갱신 + min = sum; + ans1=n1; + ans2=n2; + } + if(sum>0) { + high=mid-1; + }else { + low=mid+1; + } + } + } + } + if(ans1 q = new LinkedList(); // {r,c,h} + int[][][] map = new int[N][M][H]; + for(int i=0; i 익은 토마토 + while(!q.isEmpty()) { + boolean isChanged = false; + int size = q.size(); + while(size-->0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + int h = cur[2]; + + if(visited[r][c][h]) continue; + visited[r][c][h] = true; + if(map[r][c][h]==0) { + changeCnt++; // 토마토 익었으면 갯수 증가 + isChanged = true; // 바뀐거 체크 + } + + for(int d=0; d<4; ++d) { // 4방탐색 + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=N || nc<0 || nc>=M || visited[nr][nc][h]) continue; // 경계 및 방문 + if(map[nr][nc][h]==0) q.offer(new int[] {nr,nc,h}); + } + // 아래 탐색 + if(h>0) { + if(!visited[r][c][h-1] && map[r][c][h-1]==0) q.offer(new int[] {r,c,h-1}); + } + // 위 탐색 + if(h[] list; + static Map score; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + dice = new int[10]; + String[] str = br.readLine().split(" "); + for(int i=0; i<10; ++i) { + dice[i] = Integer.parseInt(str[i]); + } + horse = new int[4]; // 말 4개의 위치 + list = new ArrayList[33]; + for(int i=0; i<33; ++i) { + list[i] = new ArrayList(); + } + list[0].add(1); + list[1].add(2); + list[2].add(3); + list[3].add(4); + list[4].add(5); + list[5].add(6); + list[6].add(7); + list[7].add(8); + list[8].add(9); + list[9].add(10); + list[10].add(11); + list[11].add(12); + list[12].add(13); + list[13].add(14); + list[14].add(15); + list[15].add(16); + list[16].add(17); + list[17].add(18); + list[18].add(19); + list[19].add(20); + list[20].add(32); + + list[5].add(21); + list[21].add(22); + list[22].add(23); + list[23].add(24); + list[24].add(30); + + list[10].add(25); + list[25].add(26); + list[26].add(24); + + list[15].add(27); + list[27].add(28); + list[28].add(29); + list[29].add(24); + + list[30].add(31); + list[31].add(20); + + score = new HashMap(); + score.put(1, 2); + score.put(2, 4); + score.put(3, 6); + score.put(4, 8); + score.put(5, 10); + score.put(6, 12); + score.put(7, 14); + score.put(8, 16); + score.put(9, 18); + score.put(10, 20); + score.put(11, 22); + score.put(12, 24); + score.put(13, 26); + score.put(14, 28); + score.put(15, 30); + score.put(16, 32); + score.put(17, 34); + score.put(18, 36); + score.put(19, 38); + score.put(20, 40); + score.put(21, 13); + score.put(22, 16); + score.put(23, 19); + score.put(24, 25); + score.put(25, 22); + score.put(26, 24); + score.put(27, 28); + score.put(28, 27); + score.put(29, 26); + score.put(30, 30); + score.put(31, 35); + score.put(32, 0); + + dfs(0,0); + System.out.println(max); + } + + public static void dfs(int n, int sum) { + if(n==10) { + max = Math.max(max, sum); + return; + } + boolean startFlag = false; + for(int i=0; i<4; ++i) { + if(horse[i]==32) continue; // 이미 도착한 말이면 무시 + if(startFlag && horse[i]==0) continue; // 이전에 0에서 움직인 말이 있으면 다른 0에 있는 말은 무시 + int next = getNext(horse[i],dice[n]); + if(canGo(next)) { + if(horse[i]==0) startFlag = true; // 0에서 시작하는 말 있으면 체크 + int tmp = horse[i]; + horse[i] = next; // 말 움직이기 + dfs(n+1, sum+score.get(next)); + horse[i] = tmp; // 말 되돌리기 + } + } + + } + + public static int getNext(int n, int t) { // n위치에서 t만큼 이동 + int next; + // 1번 움직임 + if(n==5 || n==10 || n==15) { // 시작이 양갈래 길이면 + next = list[n].get(1); // 파란색 따라가기 + }else { + next = list[n].get(0); + } + // 나머지 t-1번 움직임 + for(int i=0; i을 떠올리자! + * 시간 복잡도 : NlogN (정렬이 NlogN 나머지는 N이므로) + */ +public class Baekjoon_18870 { + + public static void main(String[] args) throws NumberFormatException, IOException { + + // 배열 생성 후 대입 + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + StringTokenizer st = new StringTokenizer(br.readLine()," "); + for(int i=0;i map = new HashMap(); + if(flag==sortedArr[0]) { // 모든 값이 같으면 + map.put(flag,cnt++); + }else { + for(int i=0;imid) sum += trees[i]-mid; + } + if(sum>M) { + answer = mid; + low = mid+1; + }else if(sum==M){ + answer = mid; + break; + }else { + high = mid-1; + } + } + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week38/Baekjoon_11054.java" "b/src/\352\260\225\353\217\231\354\204\235/week38/Baekjoon_11054.java" new file mode 100644 index 0000000..6adc136 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week38/Baekjoon_11054.java" @@ -0,0 +1,43 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 가장 긴 바이토닉 부분 수열 +public class Baekjoon_11054 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + int[] increase = new int[N]; + int[] decrease = new int[N]; + String[] str = br.readLine().split(" "); + for(int i=0; iarr[j]) increase[i] = Math.max(increase[i], increase[j]+1); + } + } + decrease[N-1] = 1; + for(int i=N-2; i>=0; --i) { + decrease[i] = 1; + for(int j=N-1; j>i; --j) { + if(arr[i]>arr[j]) decrease[i] = Math.max(decrease[i], decrease[j]+1); + } + } + + int max = 0; + for(int i=0; i q = new LinkedList(); + q.offer(new int[] {startR,startC}); + count[startR][startC] = 0; // 시작점은 이동횟수 0 + + int answer = -1; // 답이 없을 경우 -1 + + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if(r==endR && c==endC) { // 마지막칸에 도착했으면 + break; // 이미 이동횟수가 저장되어 있으므로 종료 + } + + for(int d=0; d<4; ++d) { + for(int i=1; i<=K; ++i) { + int nr = r+i*dir[d][0]; + int nc = c+i*dir[d][1]; + int dist = count[r][c]+1; // 다음칸까지 이동횟수 + if(nr<0 || nr>=N || nc<0 || nc>=M || map[nr][nc]=='#') break; // 범위밖 또는 벽이면 종료 + if(count[nr][nc]=0) { + int num1 = ab[idx1]; + int num2 = cd[idx2]; + int sum = num1+num2; + if(sum==0) { + int cnt1 = 1; + while(idx10 && cd[idx2]==cd[idx2-1]) { // 같은 숫자 있으면 + idx2--; + cnt2++; + } + ans += (long)cnt1*cnt2; + } + if(sum<0) { + idx1++; // 증가 + }else { + idx2--; // 감소 + } + } + System.out.println(ans); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week39/Baekjoon_2618.java" "b/src/\352\260\225\353\217\231\354\204\235/week39/Baekjoon_2618.java" new file mode 100644 index 0000000..4fe6a0d --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week39/Baekjoon_2618.java" @@ -0,0 +1,75 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +// 경찰차 +/* + * 구글링하여 해결하였다. + * dp[i][j] = 1번차가 i번째, 2번차가 j번째 사건위치에 도달했을 때, 마지막까지 해결하는 최솟값이다. + * 즉 dp[0][0]을 구하기위해 dp[0][0]에서부터 재귀 방식으로 Top-Down 방식으로 해결한다. + * dp배열을 어떤식으로 설정하는지 자체가 상당히 어려웠다. + */ +public class Baekjoon_2618 { + + static int N,W; + static int[][] dp; + static int[][] pos; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + N = Integer.parseInt(br.readLine()); + W = Integer.parseInt(br.readLine()); + dp = new int[W+1][W+1]; // N이 아니라 W의 수에 맞춰 초기화 + pos = new int[W+1][2]; + for(int i=1; i<=W; ++i) { // 인덱스 1부터 + String[] str = br.readLine().split(" "); + pos[i][0] = Integer.parseInt(str[0]); + pos[i][1] = Integer.parseInt(str[1]); + } + sb.append(solve(1, 0, 0)).append("\n"); + + int idx1 = 0; // 현재 1번차의 인덱스 + int idx2 = 0; // 현재 2번차의 인덱스 + for(int i=1; i<=W; ++i) { + int moveDist1 = getDist(1, idx1, i); // 1번차가 i번째 사건 위치까지의 거리 + + if(dp[idx1][idx2] - moveDist1 == dp[i][idx2]) { + idx1 = i; + sb.append(1).append("\n"); + }else { + idx2 = i; + sb.append(2).append("\n"); + } + } + System.out.println(sb.toString()); + } + + public static int solve(int eventIdx, int idx1, int idx2) { + if(eventIdx>W) { // 사건의 인덱스가 사건 수보다 크면 종료 + return 0; + } + + if(dp[idx1][idx2]!=0) { // 계산이 되어 있으면 + return dp[idx1][idx2]; + } + + int moveDist1 = solve(eventIdx+1, eventIdx, idx2) + getDist(1, idx1, eventIdx); + int moveDist2 = solve(eventIdx+1, idx1, eventIdx) + getDist(2, idx2, eventIdx); + + return dp[idx1][idx2] = Math.min(moveDist1, moveDist2); + } + + public static int getDist(int type, int from, int to) { + if(from==0) { + if(type==1) { // 1번째 차이면 {1,1}에서 to까지 + return Math.abs(pos[to][0]-1)+Math.abs(pos[to][1]-1); + }else { // 2번째 차이면 {N,N}에서 to까지 + return Math.abs(pos[to][0]-N)+Math.abs(pos[to][1]-N); + } + } + return Math.abs(pos[from][0]-pos[to][0])+Math.abs(pos[from][1]-pos[to][1]); + } +} \ No newline at end of file diff --git "a/src/\352\260\225\353\217\231\354\204\235/week40/Baekjoon_1113.java" "b/src/\352\260\225\353\217\231\354\204\235/week40/Baekjoon_1113.java" new file mode 100644 index 0000000..bf7fcc5 --- /dev/null +++ "b/src/\352\260\225\353\217\231\354\204\235/week40/Baekjoon_1113.java" @@ -0,0 +1,88 @@ +package baekjoon; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Queue; + +// 수영장 만들기 +/* + * 테두리는 물을 채울 수 없으므로 제외하고 + * 나머지 칸중에서 높이가 1인 곳 부터 연결되어 있는 구역을 bfs로 전부 탐색해서 + * 높이를 1씩 증가시켜 나가면 된다. + * 구역을 탐색 중에 테두리가 연결되어 있거나, 높이가 낮은 부분이 근접해있으면 채울 수 없으므로 무시한다. + */ +public class Baekjoon_1113 { + + static int N,M,answer; + static int[][] map; + static boolean[][] visited; + static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String[] str = br.readLine().split(" "); + N = Integer.parseInt(str[0]); + M = Integer.parseInt(str[1]); + map = new int[N][M]; + int top = 1; + for(int i=0; i q = new LinkedList(); + ArrayList list = new ArrayList(); + boolean flag = false; // 채울 수 있는지 확인, false면 가능 true면 불가능 + q.offer(new int[] {i,j}); + while(!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if(r==0 || c==0 || r==N-1 || c==M-1) { // 테두리이면 물 채우기 불가 + flag = true; // 채우기 불가능 체크 + continue; + } + if(visited[r][c]) continue; // 방문체크 + visited[r][c] = true; + list.add(new int[] {r,c}); + for(int d=0; d<4; ++d) { + int nr = r+dir[d][0]; + int nc = c+dir[d][1]; + if(nr<0 || nr>=N || nc<0 || nc>=M || visited[nr][nc]) continue; // 경계 및 방문 + if(map[r][c]>map[nr][nc]) { // 옆칸이 높이가 낮으면 + flag = true; // 채우기 불가능 + } + if(map[r][c]==map[nr][nc]) { // 높이가 같은 칸만 추가 + q.offer(new int[] {nr,nc}); + } + } + } + if(!flag) { + for(int[] cur : list) { + map[cur[0]][cur[1]]++; // 물 높이 1씩 채우기 + answer++; // 정답 증가 + } + } + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week17/BJ_10282.java" "b/src/\352\263\265\354\234\244\355\231\230/week17/BJ_10282.java" new file mode 100644 index 0000000..defb17c --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week17/BJ_10282.java" @@ -0,0 +1,71 @@ +package d1222; + +import java.io.*; +import java.util.*; + +/* +백준 10282 해킹 + +풀이법 : + 1. 의존성을 인접리스트 형태로 저장해둡니다. + 2. 감염 정보를 pq에 딜레이시간 오름차순으로 저장 후 하나씩 감염시킵니다. + + 풀고 보니 다익스트라 문제였네요. 뭔가 신선했습니다.😎😎😎 + */ + +public class BJ_10282 { + static int testcase, n, d, c, infection, time; + static List dependency[]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + testcase = Integer.parseInt(br.readLine()); + + for (int t = 0; t < testcase; t++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + d = Integer.parseInt(st.nextToken()); + c = Integer.parseInt(st.nextToken()); + infection = time = 0; + + // 의존성 인접리스트 초기화 + // i번 감염시 해당리스트 모두 감염 + dependency = new List[n + 1]; + for (int i = 1; i < dependency.length; i++) + dependency[i] = new ArrayList<>(); + + for (int i = 0; i < d; i++) { + st = new StringTokenizer(br.readLine()); + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + dependency[b].add(new int[] { a, s }); + } + + simulate(); + System.out.println(infection + " " + time); + } + } + + static void simulate() { + PriorityQueue computer = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1])); // 감염 대기열 + boolean[] infected = new boolean[n + 1]; + computer.offer(new int[] { c, 0 }); + + while (!computer.isEmpty()) { + int[] curCom = computer.poll(); + int num = curCom[0]; + int delay = curCom[1]; + + if (infected[num]) + continue; + + infection++; + infected[num] = true; + time = delay; // 지금까지 경과시간 갱신 + + for (int[] dep : dependency[num]) + computer.offer(new int[] { dep[0], time + dep[1] }); // [컴퓨터 번호, 현재시간 + 딜레이시간] + } + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week17/BJ_2467.java" "b/src/\352\263\265\354\234\244\355\231\230/week17/BJ_2467.java" new file mode 100644 index 0000000..5a8a730 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week17/BJ_2467.java" @@ -0,0 +1,51 @@ +package d1222; + +import java.util.*; +import java.io.*; + +/* +백준 2467 용액 + +풀이법 : + 1. 투포인터를 사용해 용액 배열을 탐색합니다. + 2. 합이 음수일 때는 left++, 양수일 때는 right--를 해줍니다. + 3. 합의 절댓값이 최소일 때 용액 값을 갱신해줍니다. + + */ + +public class BJ_2467 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int sum = Integer.MAX_VALUE; + int[] solution = new int[n]; // 용액 배열 + int[] answer = new int[2]; + + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 0; i < n; i++) + solution[i] = Integer.parseInt(st.nextToken()); + + int left = 0, right = n - 1; + while (left != right) { + int tmp = solution[left] + solution[right]; + + // 두 용액 합 절댓값이 기존 최솟값보다 작을 때 + if(Math.abs(tmp) delete = new Stack<>(); // 삭제된 인덱스들 관리 + int[][] table = new int[n][2]; // 인덱스 연결관계 + boolean[] isDelete = new boolean[n]; // 삭제 여부 + int index = k; + table[0][0] = table[n - 1][1] = -1; // [][0]이 -1이면 제일 위, [][1]이 -1이면 제일 아래 + + // 인덱스 관계 초기화 + for (int i = 0; i < n; i++) { + if (i > 0) + table[i][0] = i - 1; // i 인덱스의 위는 i-1 + if (i < n - 1) + table[i][1] = i + 1; // i 인덱스의 아래는 i+1 + } + + for (String c : cmds) { + String[] cmd = c.split(" "); + int move; + + switch (cmd[0]) { + + // U, D는 해당 값만큼 테이블을 참고해서 인덱스를 이동시킨다. + case "U": + move = Integer.parseInt(cmd[1]); + for (int i = 0; i < move; i++) + index = table[index][0]; // 위의 인덱스로 한 번 이동 + break; + + case "D": + move = Integer.parseInt(cmd[1]); + for (int i = 0; i < move; i++) + index = table[index][1]; // 아래의 인덱스로 한 번 이동 + break; + + // C는 스택에 삭제할 인덱스 삽입 후 위,아래의 인덱스들을 연결시켜준다. + case "C": + delete.push(index); + isDelete[index] = true; + + int upperIndex = table[index][0]; + int lowerIndex = table[index][1]; + + + // 현재 인덱스가 제일 위 또는 아래가 아니라면 위 인덱스와 아래 인덱스 연결 + if (upperIndex != -1) + table[upperIndex][1] = table[index][1]; + + if (lowerIndex != -1) + table[lowerIndex][0] = table[index][0]; + + // 현재 인덱스가 제일 아래이면 위쪽 아니면 아래쪽 인덱스로 변경 + index = table[index][1] != -1 ? table[index][1] : table[index][0]; + + break; + + // Z는 삭제여부 변경 후, 인덱스 관계 재조정 + case "Z": + int restore = delete.pop(); + int tmp; + table[restore][0] = table[restore][1] = -1; // 위 또는 아래로 연결 못하면 제일 위 or 제일 아래 + + // 복구할 인덱스의 위쪽에 삭제되지 않은 인덱스 있으면 연결 + tmp = restore; + while (tmp > 0) { + if (!isDelete[--tmp]) { + table[tmp][1] = restore; + table[restore][0] = tmp; + break; + } + } + + // 복구할 인덱스의 아래쪽에 삭제되지 않은 인덱스 있으면 연결 + tmp = restore; + while (tmp < n - 1) { + if (!isDelete[++tmp]) { + table[tmp][0] = restore; + table[restore][1] = tmp; + break; + } + } + + isDelete[restore] = false; + break; + } + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + if (isDelete[i]) + sb.append("X"); + else + sb.append("O"); + } + + return sb.toString(); + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week19/BG_2212.java" "b/src/\352\263\265\354\234\244\355\231\230/week19/BG_2212.java" new file mode 100644 index 0000000..a3fd3bb --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week19/BG_2212.java" @@ -0,0 +1,48 @@ +package d220108; + +import java.util.*; +import java.io.*; + +/* +백준 2212 센서 + +풀이법 : + 1. 센서 좌표들을 오름차순으로 정렬합니다. + 2. 좌표간 거리가 큰 부분부터 영역을 구분하여 k개의 영역으로 쪼개줍니다. + 3. k개의 영역을 각 집중국이 담당하면 거리 합이 최소가 됩니다. + + */ + + +public class BG_2212 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int n = Integer.parseInt(br.readLine()); + int k = Integer.parseInt(br.readLine()); + int answer = 0; + int[] sensor = new int[n]; + String[] input = br.readLine().split(" "); + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o2, o1)); + + // 센서 좌표 입력 및 정렬 + for (int i = 0; i < n; i++) + sensor[i] = Integer.parseInt(input[i]); + Arrays.sort(sensor); + + // 좌표간 거리를 우선순위큐에 내림차순으로 삽입 + for (int i = 1; i < n; i++) + pq.offer(sensor[i] - sensor[i - 1]); + + // 거리가 먼 순으로 k-1개를 제거 (k개 영역 생성) + for (int i = 0; i < k - 1; i++) + pq.poll(); + + // 나머지 거리들 합 + while(!pq.isEmpty()) + answer+=pq.poll(); + + System.out.println(answer); + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week19/BJ_13460.java" "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_13460.java" new file mode 100644 index 0000000..f51ceac --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_13460.java" @@ -0,0 +1,177 @@ +package d220110; + +import java.io.*; +import java.util.*; + +/* +백준 13460 구슬탈출2 + +풀이법 : + 1. 최소거리 문제이기때문에 BFS로 접근했습니다. + 2. 맵 상태와 색별 좌표를 저장하는 클래스를 사용하고 조건대로 굴려봅니다.. + + */ + + +public class BJ_13460 { + + static int n, m, hole[]; + static int[] dr = new int[]{-1, 1, 0, 0}; + static int[] dc = new int[]{0, 0, -1, 1}; + static boolean visited[][][][]; + + static class Board { + char[][] map; + int[] blue = new int[2]; + int[] red = new int[2]; + + Board(char[][] map) { + this.map = map; + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + hole = new int[2]; + Board board = new Board(new char[n][m]); + visited = new boolean[n][m][n][m]; + + for (int i = 0; i < n; i++) { + char[] tmp = br.readLine().toCharArray(); + for (int j = 0; j < m; j++) { + board.map[i][j] = tmp[j]; + + if (tmp[j] == 'R') { + board.red[0] = i; + board.red[1] = j; + } else if (tmp[j] == 'B') { + board.blue[0] = i; + board.blue[1] = j; + } else if (tmp[j] == 'O') { + hole[0] = i; + hole[1] = j; + } + } + } + + System.out.println(bfs(board)); + } + + static int bfs(Board board) { + int answer = 0; + Queue q = new ArrayDeque<>(); + q.offer(board); + + while (answer<10&&!q.isEmpty()) { + int size = q.size(); + answer++; + + while (size-- > 0) { + Board cur = q.poll(); + + for (int d = 0; d < 4; d++) { + Board nextBoard = tilt(cur,d); + int redR = nextBoard.red[0]; + int redC = nextBoard.red[1]; + int blueR = nextBoard.blue[0]; + int blueC = nextBoard.blue[1]; + + // 빨간색만 도착했으면 지금까지 거리 리턴 + if(nextBoard==null) + return answer; + + // 파란색이 도착하지 않았을때만 다음 Board 큐에 추가 + if (blueR != -1 && blueC != -1&&!visited[redR][redC][blueR][blueC]) { + visited[redR][redC][blueR][blueC]=true; + q.offer(nextBoard); + } + } + } + } + + return -1; + } + + // d 방향으로 Board 굴리기 + static Board tilt(Board board, int d) { + Board nextBoard = new Board(copy(board.map)); + char[][] map = nextBoard.map; + nextBoard.blue = board.blue.clone(); + nextBoard.red = board.red.clone(); + boolean arrive = false; + + // 빨간색 먼저 굴리기 + if (isRedFirst(nextBoard, d)) { + tiltOneMarble(nextBoard, d, 'R'); + tiltOneMarble(nextBoard, d, 'B'); + } + + // 파란색 먼저 굴리기 + else { + tiltOneMarble(nextBoard, d, 'B'); + tiltOneMarble(nextBoard, d, 'R'); + } + + if (nextBoard.red[0] == -1 && nextBoard.red[1] == -1) arrive = true; + if (nextBoard.blue[0] == -1 && nextBoard.blue[1] == -1) arrive = false; + + // 빨간색만 도착하면 null 리턴 + if (arrive) return null; + + // 아니면 다음 맵 리턴 + else return nextBoard; + } + + // 해당 방향으로 color 구슬 굴리기 + static void tiltOneMarble(Board board, int d, char color) { + int[] pos; + if (color == 'R') pos = board.red; + else pos = board.blue; + + board.map[pos[0]][pos[1]] = '.'; + while (true) { + if (board.map[pos[0]][pos[1]] == 'O') { + pos[0] = -1; + pos[1] = -1; + break; + } + + if (board.map[pos[0] + dr[d]][pos[1] + dc[d]] == '#') { + board.map[pos[0]][pos[1]] = '#'; + break; + } + + pos[0] += dr[d]; + pos[1] += dc[d]; + } + } + + + static char[][] copy(char[][] map) { + char[][] tmp = new char[n][m]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + tmp[i][j] = map[i][j]; + } + } + return tmp; + } + + static Boolean isRedFirst(Board board, int d) { + switch (d) { + case 0: + return board.red[0] < board.blue[0]; + case 1: + return board.red[0] > board.blue[0]; + case 2: + return board.red[1] < board.blue[1]; + case 3: + return board.red[1] > board.blue[1]; + } + return false; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week19/BJ_17281.java" "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_17281.java" new file mode 100644 index 0000000..4b5481e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_17281.java" @@ -0,0 +1,99 @@ +package d220108; + +import java.io.*; +import java.util.*; + +/* +백준 17281 야구 + +풀이법 : + 1. n=9 이므로 순열을 생성하여 완전탐색으로 해결하였습니다. + 2. 순열 생성 시 4번째 자리는 항상 0(1번타자)로 고정하고 계산합니다. + + */ + +public class BJ_17281 { + + static int innings, answer, order[], players[][]; + static boolean used[]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + innings = Integer.parseInt(br.readLine()); + order = new int[9]; + used = new boolean[9]; + players = new int[innings][9]; // 이닝별 선수결과 배열 + answer = 0; + + for (int i = 0; i < innings; i++) { + StringTokenizer st = new StringTokenizer(br.readLine(), " "); + for (int p = 0; p < 9; p++) + players[i][p] = Integer.parseInt(st.nextToken()); + } + + // 4번타자 0번선수로 고정 후 순열 생성 + order[3] = 0; + used[0] = true; + perm(0); + + System.out.println(answer); + } + + static void play() { + int hitter, num = 0, score = 0; + + for (int inning = 0; inning < innings; inning++) { + boolean[] base = new boolean[4]; // 현재타자, 1루, 2루, 3루 + int out = 0; + + while (out < 3) { + hitter = order[num]; + + int hit = players[inning][hitter]; + base[0] = true; + + // 아웃 + if (hit == 0) out++; + + // 안타처리 + else { + // 3루부터 베이스+안타 합이 4 이상이면 득점 처리 + for (int b = 3; b >= 0; b--) { + if (!base[b]) continue; + + base[b] = false; + + if (b + hit > 3) score++; + else base[b + hit] = true; + } + } + + num = (num+1)%9; + } + } + answer = Math.max(answer, score); + } + + static void perm(int cnt) { + // 4번 타자는 고정이므로 패스 + if(cnt==3) { + perm(cnt+1); + return; + } + + if (cnt == 9) { + play(); + return; + } + + for (int i = 0; i < 9; i++) { + if (used[i]) continue; + + used[i] = true; + order[cnt] = i; + perm(cnt + 1); + used[i] = false; + } + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week19/BJ_2110.java" "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_2110.java" new file mode 100644 index 0000000..39c3288 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week19/BJ_2110.java" @@ -0,0 +1,62 @@ +package d220108; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +/* +백준 2110 공유기 설치 + +풀이법 : + 1. 집 좌표들을 오름차순 정렬 후, 1~ 끝집-첫집 범위로 공유기를 설치해봅니다. + 2. n = 1,000,000,000 이고 O(N^2)이므로 이분탐색으로 해결합니다. + +구글링으로 아이디어 참고했습니다. 저는 이분탐색도 연습이 필요할듯 하네요.. + */ + + +public class BJ_2110 { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int c = Integer.parseInt(st.nextToken()); + int house[] = new int[n]; + + for (int i = 0; i < n; i++) + house[i] = Integer.parseInt(br.readLine()); + + Arrays.sort(house); + + int start = 1, end = house[n - 1] - house[0], mid = (start + end) / 2; + + while (start <= end) { + // 첫 집에 공유기 설치 + int prev = house[0]; + int router = 1; + + // mid 간격으로 공유기 설치해보기 + for (int i = 1; i < n; i++) { + if (house[i] - prev >= mid) { + prev = house[i]; + router++; + } + } + + // 필요 이상으로 공유기를 설치했다면 간격을 더 넓혀본다. + if (router >= c) { + start = mid + 1; + mid = (start + end) / 2; + } + + else { + end = mid - 1; + mid = (start + end) / 2; + } + } + + System.out.println(mid); + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week19/PG_64065.java" "b/src/\352\263\265\354\234\244\355\231\230/week19/PG_64065.java" new file mode 100644 index 0000000..9040536 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week19/PG_64065.java" @@ -0,0 +1,39 @@ +package d220106; + +import java.util.*; + +/* +프로그래머스64065 튜플 + +풀이법 : + 1. 문자열을 split하고 길이 순으로 정렬합니다. + 2. 사용한 숫자들을 set으로 관리하며 튜플을 생성합니다. + + */ + + +public class PG_64065 { + public List solution(String s) { + List answer = new ArrayList<>(); + Set used = new HashSet<>(); // 튜플에 사용된 여부 판단 Set + + String[] tmp = s.substring(2, s.length()).split("\\{"); + Arrays.sort(tmp, (o1, o2) -> Integer.compare(o1.length(), o2.length())); + + for (String set : tmp) { + String[] numbers = set.substring(0, set.length() - 2).split(","); + + // 숫자들 차례로 used에 넣어보며 처음 넣는거면 튜플에 추가 + for (String number : numbers) { + int num = Integer.parseInt(number); + + if (used.add(num)) { + answer.add(num); + break; + } + } + } + + return answer; + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1062.java" "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1062.java" new file mode 100644 index 0000000..f99110e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1062.java" @@ -0,0 +1,78 @@ +package d220113; + +import java.io.*; +import java.util.*; + +/* +백준 1062 가르침 + +풀이법 : + 1. antic 5개는 기본으로 알아야 하므로 k<5일시 0, 그 외에는 모든 단어에서 5개의 알파벳을 제거합니다. + 2. 21Ck로 알파벳을 선택해 Set에 담고 단어들이 Set에 있는 문자로만 이루어지면 카운트해줍니다. + 3. 이 값을 비교해 최댓값을 갱신합니다. + +비트마스킹 문제였군요... 잊고 있었네요. + */ + +public class BJ_1062 { + + static int n, k, max; + static char a = 'a', z = 'z'; + static String[] words; + static Set ch; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(st.nextToken()); + k = Integer.parseInt(st.nextToken()); + max = 0; + words = new String[n]; + ch = new HashSet<>(); // 선택한 알파벳 Set + + if (k < 5) { + System.out.println(0); + return; + } + + // a, t, n, c, i는 기본이므로 단어에서 제거 + for (int i = 0; i < n; i++) { + words[i] = br.readLine() + .replaceAll("a", "") + .replaceAll("t", "") + .replaceAll("n", "") + .replaceAll("c", "") + .replaceAll("i", ""); + } + + comb(0, a); + System.out.println(max); + } + + static void comb(int cnt, int start) { + if (cnt == k - 5) { // 5개 알파벳은 이미 선택했음 + int canRead = 0; + + LOOP: + for (String word : words) { + for (int i = 0; i < word.length(); i++) { + if (!ch.contains(word.charAt(i))) // 해당 단어에서 한 알파벳라도 모르면 패스 + continue LOOP; + } + canRead++; + } + + max = Math.max(max, canRead); + return; + } + + for (int i = start; i < z; i++) { + if (i == 'a' || i == 'n' || i == 't' || i == 'i' || i == 'c') + continue; + ch.add((char) i); + comb(cnt + 1, i + 1); + ch.remove((char) i); // 배열에 덮어쓰는 형식이 아니기 때문에 제거도 해줌 + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1300.java" "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1300.java" new file mode 100644 index 0000000..c376e4d --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_1300.java" @@ -0,0 +1,47 @@ +package d220112; + +import java.util.Scanner; + +/* +백준 1300 k번째 수 + +풀이법 : + 1. 오름차순 정렬이므로 k번째 수는 1~k 입니다. + 2. 이 사이의 수들을 이분탐색하여 k번째 수를 계산해줍니다. + +이분탐색 너무 어렵네요... + */ + + +public class BJ_1300 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + int k = sc.nextInt(); + + int start = 1, end = k; + int result = 0; + + while (start <= end) { + int mid = (start + end) / 2; + long order = 0; // mid 이하인 수들의 개수 + + // i행 = i배수 + // i행에서 mid 보다 작은 수의 개수는 mid/i 이다. + // 이때 n*n이므로 mid/i와 n 중 최솟값이 해당 행에서 mid보다 작은 수의 개수이다. + for (int i = 1; i <= n; i++) { + order += Math.min(mid / i, n); + } + + if (order < k) { + start = mid + 1; + + } else { + end= mid - 1; + result=mid; + } + } + + System.out.println(result); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week20/BJ_16234.java" "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_16234.java" new file mode 100644 index 0000000..fa07784 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_16234.java" @@ -0,0 +1,106 @@ +package d220115; + +import java.io.*; +import java.util.*; + +/* +백준 16234 인구 이동 + +풀이법 : + 1. dfs로 조건에 맞는 지역들을 그룹지어 좌표와 인구수를 계산합니다. + 2. 새로운 map에 이동시킨 인구들을 저장시킵니다. + 3. 한 번이라도 이동을 못시킬때까지 반복합니다. + + */ + + +public class BJ_16234 { + + static int n, l, r, total, answer, map[][]; + static boolean flag, visited[][]; + static int dr[] = new int[]{-1, 1, 0, 0}; + static int dc[] = new int[]{0, 0, -1, 1}; + + static Queue pos; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(st.nextToken()); + l = Integer.parseInt(st.nextToken()); + r = Integer.parseInt(st.nextToken()); + map = new int[n][n]; + answer = 0; + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) + map[i][j] = Integer.parseInt(st.nextToken()); + } + + + while (true) { + visited = new boolean[n][n]; + int[][] next = new int[n][n]; + flag = false; // 인구 이동시킬때 true + + // map 전체 dfs로 연합 국가들 탐색 + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) { + if (visited[i][j]) + continue; + + total = 0; // 연합 인구 수 + pos = new ArrayDeque<>(); // 연합 국가 좌표 + dfs(i, j); // 연합 국가 탐색 + move(next); // pos에 있는 좌표들 next에 이동 + } + + if (!flag) break; // 한번도 이동 못하면 종료 + + answer++; + map = next; // 완성된 next를 map에 저장 + } + System.out.println(answer); + } + + static void dfs(int i, int j) { + visited[i][j] = true; + total += map[i][j]; + pos.offer(new int[]{i, j}); + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (oob(nr, nc)) + continue; + + // 차이가 조건에 안맞으면 건너뛰기 + int dif = Math.abs(map[i][j] - map[nr][nc]); + if (dif < l || dif > r) + continue; + + // 하나라도 연결된 국가 있으면 flag true + if (!visited[nr][nc]) { + flag = true; + dfs(nr, nc); + } + } + } + + // pos 좌표들에 인구수 배분 + static void move(int[][] next) { + int people = total / pos.size(); + + while (!pos.isEmpty()) { + int[] p = pos.poll(); + next[p[0]][p[1]] = people; + } + } + + static boolean oob(int i, int j) { + return i < 0 || j < 0 || i == n || j == n; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week20/BJ_2533.java" "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_2533.java" new file mode 100644 index 0000000..96d955d --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week20/BJ_2533.java" @@ -0,0 +1,62 @@ +package d220116; + +import java.io.*; +import java.util.*; + +/* +백준 2533 사회망 서비스(SNS) + +풀이법 : + 1. 본인이 얼리X -> 자식은 무조건 얼리 / 얼리O -> 자식은 얼리 일수도아닐수도 + 2. 본인이 얼리일때는 자식의 두가지 경우중 얼리 수가 적은 놈을 택합니다. + 3. bottom-up 방식으로 dp 테이블을 채워갑니다. + + */ + + +public class BJ_2533 { + + static boolean visited[]; + static int n, dp[][]; + static ArrayList[] graph; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + graph = new ArrayList[n + 1]; + dp = new int[n + 1][2]; // dp 테이블 0: 얼리X, 1: 얼리 + visited = new boolean[n + 1]; + + for (int i = 0; i < n + 1; i++) { + graph[i] = new ArrayList<>(); + } + + for (int i = 0; i < n - 1; i++) { + StringTokenizer st = new StringTokenizer(br.readLine(), " "); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + graph[from].add(to); + graph[to].add(from); + } + + dfs(1); + System.out.println(Math.min(dp[1][0], dp[1][1])); + } + + static void dfs(int num) { + visited[num] = true; + dp[num][0] = 0; // 내가 얼리가 아닐 때 + dp[num][1] = 1; // 내가 얼리이므로 +1 + + for (int child : graph[num]) { + if (!visited[child]) { + dfs(child); + + dp[num][0] += dp[child][1]; // 내가 얼리아니면 자식들은 무조건 얼리 + dp[num][1] += Math.min(dp[child][0], dp[child][1]); // 내가 얼리면 둘 중 최솟값 + } + } + } +} + + diff --git "a/src/\352\263\265\354\234\244\355\231\230/week20/PG_17683.java" "b/src/\352\263\265\354\234\244\355\231\230/week20/PG_17683.java" new file mode 100644 index 0000000..b929e4c --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week20/PG_17683.java" @@ -0,0 +1,81 @@ +package d220111; + +import java.util.*; + +/* +프로그래머스17683 방금그곡 + +풀이법 : + 1. #음은 소문자로 치환해줍니다. + 2. N<=1439이기 때문에 이중루프로 패턴을 검색했습니다. + + */ + + +public class PG_17683 { + + String solution(String m, String[] musicinfos) { + List thatSong = new ArrayList<>(); + int max = 0; + + // 패턴 변환 + m = m + .replaceAll("C#", "c") + .replaceAll("D#", "d") + .replaceAll("F#", "f") + .replaceAll("G#", "g") + .replaceAll("A#", "a"); + + for (String musicInfo : musicinfos) { + String[] info = musicInfo.split(","); + + int playtime = 60 * (Integer.parseInt(info[1].substring(0, 2)) - Integer.parseInt(info[0].substring(0, 2))) + + (Integer.parseInt(info[1].substring(3, 5)) - Integer.parseInt(info[0].substring(3, 5))); + String title = info[2]; + String melody = info[3]; + // 곡 멜로디 변환 + melody = melody + .replaceAll("C#", "c") + .replaceAll("D#", "d") + .replaceAll("F#", "f") + .replaceAll("G#", "g") + .replaceAll("A#", "a"); + + // 총 플레이시간에 맞게 멜로디 이어붙이기 + String totalMelody = ""; + int len = melody.length(); + for (int i = 0; i < playtime; i++) + totalMelody += melody.charAt(i % len); + + // 패턴보다 전체멜로디가 작다면 넘어가기 + if (totalMelody.length() < m.length()) continue; + + LOOP: + for (int i = 0; i <= totalMelody.length() - m.length(); i++) { + for (int j = 0; j < m.length(); j++) { + + if (totalMelody.charAt(i + j) == m.charAt(j)) { + // 마지막까지 일치할 때 + if (j == m.length() - 1) { + if (playtime >= max) { + // 최고 플레이시간이면 List 초기화 + if (playtime > max) { + max = playtime; + thatSong = new ArrayList<>(); + } + thatSong.add(title); + } + break LOOP; + } + continue; + } + + // 패턴 일치 안하면 바로 다음인덱스로 + break; + } + } + } + + return thatSong.size() == 0 ? "(None)" : thatSong.get(0); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week21/BJ_11082.java" "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_11082.java" new file mode 100644 index 0000000..12113ee --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_11082.java" @@ -0,0 +1,68 @@ +package d220120; + +import java.io.*; +import java.util.*; + +/* +백준11085 군사 이동 + +풀이법 : + 1. c에서 BFS로 탐색을 시작하되 큐 대신 우선순위 큐를 이용해 weight가 큰 값부터 탐색합니다. + 2. 최솟값을 갱신해가다가 v에 도착하면 종료합니다. + + */ + +public class BJ_11082 { + + static int p, w, c, v, answer; + static boolean[] visited; + static ArrayList[] graph; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine(), " "); + p = Integer.parseInt(st.nextToken()); + w = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine(), " "); + c = Integer.parseInt(st.nextToken()); + v = Integer.parseInt(st.nextToken()); + graph = new ArrayList[p]; + visited = new boolean[p]; + answer = Integer.MAX_VALUE; + PriorityQueue pq = new PriorityQueue<>(((o1, o2) -> Integer.compare(o2[1], o1[1]))); // weight 내림차순으로 정렬 + + for (int i = 0; i < p; i++) { + graph[i] = new ArrayList<>(); + } + + for (int i = 0; i < w; i++) { + st = new StringTokenizer(br.readLine(), " "); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int weight = Integer.parseInt(st.nextToken()); + + graph[from].add(new int[]{to, weight}); + graph[to].add(new int[]{from, weight}); + } + + pq.offer(new int[]{c,50001}); // 시작점 pq에 삽입 + + while (!pq.isEmpty()) { + int[] cur = pq.poll(); + int from = cur[0]; + int weight = cur[1]; + visited[from] = true; + answer = Math.min(answer, weight); // 너비 좁은 길 갱신 + + // v에 도착하면 종료 + if (from == v) + break; + + for (int[] next : graph[from]) { + if (visited[next[0]]) continue; + pq.offer(next); + } + } + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week21/BJ_1700.java" "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_1700.java" new file mode 100644 index 0000000..6c2713e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_1700.java" @@ -0,0 +1,70 @@ +package d220123; + +import java.io.*; +import java.util.*; + +/* +백준1700 멀티탭 스케줄링 + +풀이법 : + 1. 콘센트는 Set으로 관리하고 각 기기별 큐를 두어 몇번째에 꽂히는지 관리합니다. + 2. 콘센트가 아직 남았거나 이미 꽂혀있는 기기라면 Set에 기기번호를 추가하고 큐에서 하나 빼줍니다. + 3. 콘센트가 다 찼고 새로운 기기라면 꽂힌 기기중 가장 나중에 꽂힐 예정인 기기를 빼줍니다. + + */ + + +public class BJ_1700 { + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + int[] order = new int[k]; // 기기 들어오는 순서 + int answer = 0; + Set outlet = new HashSet<>(); // 현재 콘센트에 꽂힌 기기 + HashMap> electronic = new HashMap<>(); // 각 기기별 예정된 인덱스 + + // 입력 처리 + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < k; i++) { + int num = Integer.parseInt(st.nextToken()); + order[i] = num; + + if (!electronic.containsKey(num)) { + electronic.put(num, new ArrayDeque<>()); + } + electronic.get(num).offer(i); + } + + for (int i = 0; i < k; i++) { + int num = order[i]; + + // 콘센트에 꽉차있고 새로운 기기일 때 스케줄링 + if (outlet.size() == n && !outlet.contains(num)) { + int unplug = 0; + int farIdx = 0; + + // 콘센트에 꽂힌 기기들 확인하기 + for (int key : outlet) { + ArrayDeque elec = electronic.get(key); + int next = elec.isEmpty() ? 101 : elec.peek(); // 큐에 더이상 없다면 101 or 제일 최근에 예정된 인덱스 + + // 제일 멀리 남은 인덱스와 기기번호 갱신 + if (next > farIdx) { + farIdx = next; + unplug = key; + } + } + outlet.remove(unplug); // 제일 나중에 나올 예정인 기기 언플러그 + answer++; + } + + // 콘센트 set에 기기번호 추가하고 해당 기기 큐에서 인덱스 하나 빼주기 + outlet.add(num); + electronic.get(num).poll(); + } + + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week21/BJ_17136.java" "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_17136.java" new file mode 100644 index 0000000..769f37f --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_17136.java" @@ -0,0 +1,106 @@ +package d220122; + +import java.util.*; +import java.io.*; + +/* +백준17136 색종이 붙이기 + +풀이법 : + 1. 모든 크기 색종이를 놓아보며 완전탐색으로 해결하였습니다. + 2. 보드를 탐색하다 커버되지 않은 점을 만나면 1~5 색종이를 놓아보고 불가능하면 다음 크기 색종이는 보지 않습니다. + 3. 주어진 개수 내에서 커버를 완료하면 answer 최솟값을 갱신합니다. + + */ + + +public class BJ_17136 { + + static int answer, used[]; + static boolean[][] board; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + board = new boolean[10][10]; + answer = Integer.MAX_VALUE; + used = new int[6]; + + for (int i = 0; i < 10; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int j = 0; j < 10; j++) { + board[i][j] = st.nextToken().equals("0"); // 보드에서 0이면 커버된곳이므로 true + } + } + + dfs(0); + System.out.println(answer == Integer.MAX_VALUE ? -1 : answer); // 한번도 갱신 못했으면 -1 + } + + static void dfs(int cnt) { + // 끝점 도착했으면 사용한 색종이 수 갱신 + if (cnt == 100) { + int sum = 0; + for (int i = 1; i <= 5; i++) { + sum += used[i]; + } + answer = Math.min(answer, sum); + return; + } + + int r = cnt / 10; + int c = cnt % 10; + + // 커버된 점이면 바로 다음 칸으로 + if (board[r][c]) { + dfs(cnt + 1); + return; + } + + // 해당 칸에 1~5 색종이를 놓아본다. + for (int paper = 1; paper <= 5; paper++) { + // 놓은 색종이가 범위 밖이면 종료 + if (r + paper > 10 || c + paper > 10) + return; + + // 해당 크기 5개 다 썼으면 다음 크기로 + if (used[paper] == 5) + continue; + + // 해당 크기 놓는게 불가능하면 종료 + if (!check(cnt, paper)) + return; + + used[paper]++; + cover(cnt, paper); // 커버영역 보드에 표시 + dfs(cnt + 1); + used[paper]--; + cover(cnt, paper); // 표시한거 되돌리기 + } + } + + // 해당 위치를 왼쪽 상단으로 하여 paper 크기 놓을 수 있는지 판단 + static boolean check(int cnt, int paper) { + int r = cnt / 10; + int c = cnt % 10; + + for (int i = r; i < r + paper; i++) { + for (int j = c; j < c + paper; j++) { + if (board[i][j]) // 한곳이라도 커버된 곳 있으면 false + return false; + } + } + return true; + } + + // 해당 지점을 왼쪽 상단으로 true false XOR 연산 + static void cover(int cnt, int paper) { + int r = cnt / 10; + int c = cnt % 10; + + for (int i = r; i < r + paper; i++) { + for (int j = c; j < c + paper; j++) { + board[i][j] = !board[i][j]; + } + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week21/BJ_4811.java" "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_4811.java" new file mode 100644 index 0000000..a206ace --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week21/BJ_4811.java" @@ -0,0 +1,48 @@ +package d220120; + +import java.util.*; + +/* +백준 4811 알약 + +풀이법 : + 1. 2차원 배열 dp[][]를 먼저 30까지 채워줍니다. dp[h][w] = h를 h개, w를 w개 선택한 문자열 개수 + 2. 점화식: dp[h][w] = dp[h-1][w]+dp[h][w-1] + + */ + + +public class BJ_4811 { + + public static void main(String[] args) throws Exception { + Scanner sc = new Scanner(System.in); + long[][] dp; + dp = new long[31][31]; + + for (int h = 0; h <= 30; h++) { + for (int w = 0; w <= 30; w++) { + // h를 0개 고르면 문자열 종류는 항상 1 ex)w, ww, www... + if (h == 0) { + dp[h][w] = 1; + continue; + } + + // h를 더 많이 고를수는 없음 + if (h > w) { + dp[h][w] = 0; + } else { + dp[h][w] = dp[h - 1][w] + dp[h][w - 1]; + } + } + } + + while (true) { + int n = sc.nextInt(); + + if (n == 0) + return; + + System.out.println(dp[n][n]); + } + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week21/PG_17686.java" "b/src/\352\263\265\354\234\244\355\231\230/week21/PG_17686.java" new file mode 100644 index 0000000..edebcff --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week21/PG_17686.java" @@ -0,0 +1,97 @@ +package d220118; + +import java.util.*; + +/* +프로그래머스17686 파일명 정렬 + +풀이법 : + 1. String을 파싱하여 File 클래스에 저장합니다. + 2. 이떄 head 값은 대문자들의 인덱스를 upper 리스트에 저장하고 lowercase로 변환해줍니다. + 3. File 클래스를 담은 리스트를 조건에 맞게 정렬해줍니다. + 4. 정렬된 File에서 파일명을 복원하고 upper를 참고하여 대문자로 변환시켜줍니다. + */ + + +public class PG_17686 { + + public class File { + String head; + String number; + String tail; + ArrayList upper; + + public File(String head, String number, String tail, ArrayList upper) { + this.head = head; + this.number = number; + this.tail = tail; + this.upper = upper; + } + } + + public List solution(String[] files) { + ArrayList answer = new ArrayList<>(); + ArrayList list = new ArrayList<>(); + + for (String file : files) { + String head = null; + String number = null; + String tail = null; + ArrayList upper = new ArrayList<>(); + int i = 0; + int j = 0; + + // 첫 숫자가 나오는 인덱스 탐색 및 대문자 위치 파악 + for (; i < file.length(); i++) { + char c = file.charAt(i); + if ('A' <= c && c <= 'Z') + upper.add(i); + if (0 <= c - '0' && c - '0' <= 9) { + j = i; + break; + } + } + + // NUMBER가 끝나는 인덱스 탐색 + for (; j < file.length(); j++) { + char c = file.charAt(j); + if (c - '0' < 0 || 9 < c - '0') { + break; + } + } + + // 탐색한 인덱스를 참고하여 File 객체 리스트 생성 + head = file.substring(0, i).toLowerCase(); // 소문자로 변환 + number = file.substring(i, j); + tail = file.substring(j, file.length()); + list.add(new File(head, number, tail, upper)); + } + + // 조건에 맞게 파일명 정렬 + list.sort(((o1, o2) -> { + if (!o1.head.equals(o2.head)) + return o1.head.compareTo(o2.head); + + int o1n = Integer.parseInt(o1.number); + int o2n = Integer.parseInt(o2.number); + if (o1n != o2n) + return Integer.compare(o1n, o2n); + + return 0; + })); + + // 정렬된 리스트에서 파일명들 복구 + for (File file : list) { + char[] headChar = file.head.toCharArray(); + String number = file.number; + String tail = file.tail; + ArrayList upper = file.upper; + + for (int idx : upper) { + headChar[idx] += 'A' - 'a'; + } + answer.add(new String(headChar) + number + tail); + } + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week22/BJ_1197.java" "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_1197.java" new file mode 100644 index 0000000..e6f1a63 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_1197.java" @@ -0,0 +1,68 @@ +package d220204; + +import java.io.*; +import java.util.*; + +/* +백준1197 최소 스패닝 트리 + +풀이법 : + 기본적인 MST 문제였습니다. 크루스칼 알고리즘을 활용해 해결하였습니다. + + */ + + +public class BJ_1197 { + + static int v, e, answer; + static List[] graph; + static boolean visited[]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + v = Integer.parseInt(st.nextToken()); + e = Integer.parseInt(st.nextToken()); + answer = 0; + visited = new boolean[v + 1]; + graph = new List[v + 1]; + + for (int i = 1; i <= v; i++) { + graph[i] = new ArrayList<>(); + } + + for (int i = 0; i < e; i++) { + st = new StringTokenizer(br.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + + graph[from].add(new int[]{to, w}); + graph[to].add(new int[]{from, w}); + } + + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1])); + pq.offer(new int[]{1, 0}); + + while (!pq.isEmpty() && v > 0) { + int[] cur = pq.poll(); + int to = cur[0]; + int w = cur[1]; + + if (visited[to]) { + continue; + } + + answer+=w; + v--; + visited[to] = true; + + for(int[] next : graph[to]){ + pq.add(next); + } + } + + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week22/BJ_12851.java" "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_12851.java" new file mode 100644 index 0000000..e553bf5 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_12851.java" @@ -0,0 +1,65 @@ +package d220129; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayDeque; +import java.util.Queue; +import java.util.StringTokenizer; + +/* +백준12851 숨바꼭질2 + +풀이법 : + 1. BFS를 사용해 k점까지 탐색해봅니다. + + */ + + +public class BJ_12851 { + + public static void main(String[] args) throws Exception { + StringTokenizer st = new StringTokenizer( + new BufferedReader(new InputStreamReader(System.in)).readLine()); + boolean[] visited = new boolean[100001]; + + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + int time = -1; + int route = 0; + Queue q = new ArrayDeque<>(); + q.offer(n); + + // 큐가 비거나 루트가 생기면 종료 + while (!q.isEmpty() && route == 0) { + int size = q.size(); + time++; + + // 같은 시간에 도착하는 경로들 + while (size-- > 0) { + int cur = q.poll(); + visited[cur] = true; + int[] next = new int[3]; + + // 도착하면 경로 카운트 + if (cur == k) { + route++; + continue; + } + + next[0] = cur - 1; + next[1] = cur + 1; + next[2] = cur * 2; + + for (int i = 0; i < 3; i++) { + if (next[i] < 0 || next[i] > 100000 || visited[next[i]]) { + continue; + } + q.add(next[i]); + } + } + } + + System.out.println(time); + System.out.println(route); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week22/BJ_14950.java" "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_14950.java" new file mode 100644 index 0000000..f040235 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_14950.java" @@ -0,0 +1,72 @@ +package d220207; + +import java.io.*; +import java.util.*; + +/* +백준14950 정복자 + +풀이법 : + 1. MST를 구성하면서 증가할 비용을 미리 더해놓습니다. + 2. 일반적인 MST를 계산합니다. + + */ + + +public class BJ_14950 { + + static int n, m, t; + static List[] city; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = null; + + st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + t = Integer.parseInt(st.nextToken()); + city = new List[n+1]; + + for (int i = 1; i < n + 1; i++) { + city[i] = new ArrayList<>(); + } + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + + city[from].add(new int[]{to, w}); + city[to].add(new int[]{from, w}); + } + + int mst = ((t + t * (n - 2)) * (n - 2)) / 2; // 도시를 정복하며 추가될 비용들 미리 더해놓기 + boolean visited[] = new boolean[n + 1]; + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[1], o2[1])); + pq.offer(new int[]{1, 0}); + + // 크루스칼 알고리즘 + while (!pq.isEmpty() && n > 0) { + int[] cur = pq.poll(); + int edge = cur[0]; + int w = cur[1]; + + if(visited[edge]) + continue; + + visited[edge]=true; + mst+=w; + n--; + + for(int[] adj : city[edge]){ + if (!visited[adj[0]]) { + pq.offer(adj); + } + } + } + + System.out.println(mst); + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week22/BJ_2933.java" "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_2933.java" new file mode 100644 index 0000000..bf0d4ae --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week22/BJ_2933.java" @@ -0,0 +1,197 @@ +package d220207; + +import java.io.*; +import java.util.*; + +/* +백준2933 미네랄 + +풀이법 : + 1. 막대기 위치의 미네랄을 제거합니다. + 2. 제거한 위치의 사방을 탐색하여 각각 dfs를 태워보고 바닥과 닿지 않은 덩어리이면 떨어뜨려야합니다. + 3. 해당 덩어리 좌표들을 왼쪽, 아래 순으로 정렬하고 각 바닥 좌표들이 떨어지는 거리의 최솟값을 구합니다. + 4. 클러스터를 최솟값만큼 내려줍니다. + + */ + + +public class BJ_2933 { + + static int r, c, n; + static char[][] map; + static List pos; + static int dr[] = {1, -1, 0, 0,}; + static int dc[] = {0, 0, -1, 1}; + static boolean visited[][]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + r = Integer.parseInt(st.nextToken()); + c = Integer.parseInt(st.nextToken()); + map = new char[r][c]; + for (int i = 0; i < r; i++) { + map[i] = br.readLine().toCharArray(); + } + n = Integer.parseInt(br.readLine()); + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < n; i++) { + int targetR = r - Integer.parseInt(st.nextToken()); + int targetC = -1; + + // 왼쪽에서 막대기 + if (i % 2 == 0) { + for (int j = 0; j < c; j++) { + if (map[targetR][j] == 'x') { + targetC = j; + break; + } + } + } + + // 오른쪽에서 막대기 + else { + for (int j = c - 1; j >= 0; j--) { + if (map[targetR][j] == 'x') { + targetC = j; + break; + } + } + } + + // 맞은 미네랄 없으면 넘어가기 + if (targetC == -1) + continue; + + // 해당 좌표 미네랄 부수고 클러스터 체크 + map[targetR][targetC] = '.'; + checkCluster(targetR, targetC); + } + + printMap(); + } + + // checkCluster: 해당 좌표에서 사방으로 각각 클러스터 체크 + static void checkCluster(int targetR, int targetC) { + + for (int d = 0; d < 4; d++) { + int nr = targetR + dr[d]; + int nc = targetC + dc[d]; + + if (oob(nr, nc) || map[nr][nc] == '.') { + continue; + } + + pos = new ArrayList<>(); // 클러스터 이루는 좌표 + visited = new boolean[r][c]; + + // 해당 방향 클러스터가 바닥에 닿지 않으면 떨어질 depth 계산후 떨어뜨리기 + if (clustering(nr, nc)) { + int depth = checkFallDepth(); + fallMineral(depth); + break; + } + } + } + + // clustering: 좌표가 하나라도 바닥에 닿으면 false를 반환하는 DFS + static boolean clustering(int i, int j) { + + if (i == r - 1) { + return false; + } + + visited[i][j] = true; + pos.add(new int[]{i, j}); + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (oob(nr, nc)) { + continue; + } + + if (!visited[nr][nc] && map[nr][nc] == 'x' && !clustering(nr, nc)) { + return false; + } + } + return true; + } + + // checkFallDepth: 클러스터를 이루는 pos에서 바닥 좌표들 중 제일 짧게 떨어지는 값 반환 + static int checkFallDepth() { + + int depth = Integer.MAX_VALUE; + Set checkedCol = new HashSet<>(); + + // 클러스터 좌표들을 왼쪽아래 순으로 정렬 + pos.sort((o1,o2)->{ + if (o1[1] != o2[1]) { + return Integer.compare(o1[1], o2[1]); + } + return Integer.compare(o2[0],o1[0]); + }); + + for (int[] bottomPos : pos) { + int i = bottomPos[0]; + int j = bottomPos[1]; + int tmp = 0; + + // 한 column당 바닥은 하나임 + if(checkedCol.contains(j)) + continue; + + checkedCol.add(j); + + while (i + 1 < r) { + if (map[++i][j] == 'x') { + break; + } + tmp++; + } + + // 바닥까지의 거리들 중 제일 짧은 값 + depth = Math.min(depth, tmp); + } + + return depth; + } + + // fallMineral: 클러스터 좌표들 .으로 바꾸고 depth만큼 다시 내리기 + static void fallMineral(int depth) { + clearMineral(); + + for (int[] cur : pos) { + int i = cur[0] + depth; + int j = cur[1]; + + map[i][j] = 'x'; + } + } + + static void clearMineral() { + + for (int[] cur : pos) { + int i = cur[0]; + int j = cur[1]; + + map[i][j] = '.'; + } + } + + static boolean oob(int i, int j) { + return i < 0 || j < 0 || i == r || j == c; + } + + static void printMap() { + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + System.out.print(map[i][j]); + } + System.out.println(); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week22/PG_17677.java" "b/src/\352\263\265\354\234\244\355\231\230/week22/PG_17677.java" new file mode 100644 index 0000000..17b24b7 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week22/PG_17677.java" @@ -0,0 +1,76 @@ +package d220203; + +/* +프로그래머스17677 뉴스 클러스터링 + +풀이법 : + 1. Map으로 원소 개수들을 관리해주고 조건에 맞게 합/교집합 원소 수를 계산해줍니다. + +쉬운 문제에 삽질을 너무 했네요... 항상 문제는 꼼꼼히ㅠ + */ + +import java.util.*; + +public class PG_17677 { + + int solution(String str1, String str2) { + str1 = str1.toLowerCase(Locale.ROOT); + str2 = str2.toLowerCase(Locale.ROOT); + + Map first = makeJaccard(str1); + Map second = makeJaccard(str2); + + double union = 0; + double intersection = 0; + + for (String key : first.keySet()) { + union += first.get(key); + } + + for (String key : second.keySet()) { + if (first.containsKey(key)) { + int firstVal = first.get(key); + int secondVal = second.get(key); + intersection += Math.min(firstVal, secondVal); + + if (secondVal >= firstVal) { + union += secondVal - firstVal; + } + + } else { + union += second.get(key); + } + } + + if (intersection == 0 && union == 0) { + return 1; + } + + return (int) (intersection / union * 65536); + } + + Map makeJaccard(String str) { + + Map map = new HashMap<>(); + + for (int i = 0; i < str.length() - 1; i++) { + if (!isAlpha(str.charAt(i)) || !isAlpha(str.charAt(i + 1))) { + continue; + } + + String element = str.substring(i, i + 2); + + if (!map.containsKey(element)) { + map.put(element, 0); + } + + map.put(element, map.get(element) + 1); + } + + return map; + } + + boolean isAlpha(char c) { + return 'a' <= c && c <= 'z'; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week23/BJ_1043.java" "b/src/\352\263\265\354\234\244\355\231\230/week23/BJ_1043.java" new file mode 100644 index 0000000..9292a99 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week23/BJ_1043.java" @@ -0,0 +1,90 @@ +package d220221; + +import java.io.*; +import java.util.*; + +/* +백준1043 거짓말 + +풀이법 : + 1. 진실을 아는 사람을 Set으로 관리합니다. + 2. 파티에 진실을 아는 사람이 한 명이라도 있으면 해당 파티에 참가한 모든 사람을 Set에 추가합니다. + 3. Set에 새로운 사람이 추가되지 않을 때까지 반복합니다. + + */ + + +public class BJ_1043 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n, m, k, answer; + boolean flag; + + Set knowReal = new HashSet<>(); // 진실을 아는 사람 Set + List> parties = new ArrayList<>(); // 파티 참가자 + + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + boolean[] checked = new boolean[n+1]; + answer = 0; + + st = new StringTokenizer(br.readLine()); + k = Integer.parseInt(st.nextToken()); + for (int i = 0; i < k; i++) { + int num = Integer.parseInt(st.nextToken()); + knowReal.add(num); + checked[num] = true; + } + + for (int i = 0; i < m; i++) { + parties.add(new ArrayList<>()); + st = new StringTokenizer(br.readLine()); + st.nextToken(); + while (st.hasMoreTokens()) { + parties.get(i).add(Integer.parseInt(st.nextToken())); + } + } + + while (true) { + flag = false; + + for (List party : parties) { + for (int person : party) { + // 해당 파티에서 한 명이라도 진실을 안다면 + if (knowReal.contains((person))) { + for (int know : party) { + + // 이미 알고있는 사람은 패스 + if(checked[know]) + continue; + + knowReal.add(know); + checked[know] = true; + flag = true; + } + break; + } + } + } + + // 진실 아는사람 더이상 업데이트 안되면 종료 + if (!flag) { + break; + } + } + + LOOP: + for (List party : parties) { + for (int person : party) { + if (knowReal.contains((person))) { + continue LOOP; + } + } + answer++; + } + + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week23/PG_42842.java" "b/src/\352\263\265\354\234\244\355\231\230/week23/PG_42842.java" new file mode 100644 index 0000000..2288aeb --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week23/PG_42842.java" @@ -0,0 +1,26 @@ +package d220221; + +public class PG_42842 { + + public int[] solution(int brown, int yellow) { + int[] answer = new int[2]; + int n = brown + yellow; + + for (int i = n - 1; i > 1; i--) { + if (n % i != 0) { + continue; + } + + int w = i; + int h = n / i; + + if ((w - 2) * (h - 2) == yellow) { + answer[0] = w; + answer[1] = h; + break; + } + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week24/BJ_20055.java" "b/src/\352\263\265\354\234\244\355\231\230/week24/BJ_20055.java" new file mode 100644 index 0000000..d48c181 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week24/BJ_20055.java" @@ -0,0 +1,98 @@ +package d220227; + +import java.util.*; +import java.io.*; + +/* +백준20055 컨베이어 벨트 위의 로봇 + +풀이법 : + 1. 벨트를 2차원 배열로 내구도, 로봇유무를 관리하고 시작, 끝점을 투포인터로 관리합니다. + 2. step 별로 실행해줍니다. + + */ + + +public class BJ_20055 { + + static int n, k, start, end, belt[][]; // [[내구도, 로봇], []...] + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + k = Integer.parseInt(st.nextToken()); + start = 0; + end = n - 1; + belt = new int[2 * n][2]; + int level = 0; + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < 2 * n; i++) { + belt[i][0] = Integer.parseInt(st.nextToken()); + } + + while (true) { + level++; + step1(); // 벨트 회전 + step2(); // 로봇 이동 + step3(); // 시작에 로봇 올리기 + + // 종료 체크 + if (step4()) break; + } + + System.out.println(level); + } + + static void step1() { + + start = (start - 1 + 2 * n) % (2 * n); + end = (end - 1 + 2 * n) % (2 * n); + checkArrive(); + } + + static void step2() { + + for (int i = 1; i < n; i++) { + int current = (end - i + 2 * n) % (2 * n); + int next = (current + 1) % (2 * n); + + if (belt[current][1] == 1 && belt[next][1] == 0 && belt[next][0] > 0) { + belt[current][1] = 0; + belt[next][1] = 1; + belt[next][0]--; + checkArrive(); + } + } + } + + static void step3() { + + if (belt[start][0] > 0) { + belt[start][1] = 1; + belt[start][0]--; + } + } + + static boolean step4() { + + int cnt = 0; + + for (int i = 0; i < 2 * n; i++) { + if (belt[i][0] == 0) { + cnt++; + } + } + + return cnt >= k; + } + + // 끝점 로봇 체크 + static void checkArrive() { + + if (belt[end][1] == 1) { + belt[end][1] = 0; + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week24/BJ_2616.java" "b/src/\352\263\265\354\234\244\355\231\230/week24/BJ_2616.java" new file mode 100644 index 0000000..442772d --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week24/BJ_2616.java" @@ -0,0 +1,53 @@ +package d220228; + +import java.io.*; +import java.util.*; + +/* +백준2616 소형기관차 + +풀이법 : + 1. 2차원 dp 배열을 선언해줍니다. + 2. 기관차가 1개일때, 2개, 3개일때를 차례로 dp 배열을 채워줍니다. + + */ + + +public class BJ_2616 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int train[] = new int[n]; + int sum[] = new int[n]; + + // 열차 입력 및 누적합 초기화 + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 0; i < n; i++) { + train[i] = Integer.parseInt(st.nextToken()); + if (i == 0) { + sum[i] = train[i]; + } else { + sum[i] = sum[i - 1] + train[i]; + } + } + + int k = Integer.parseInt(br.readLine()); + + int[][] dp = new int[4][n]; + dp[1][k - 1] = sum[k - 1]; + dp[2][2 * k - 1] = sum[2 * k - 1]; + dp[3][3 * k - 1] = sum[3 * k - 1]; + + for (int i = 1; i < 4; i++) { + for (int j = i * k; j < n; j++) { + // 열차 i개 + // j를 끝으로 하는 열차 놓아보기 + // 안놓고 j-1까지의 최댓값 vs 새로 열차 놓고 + 그 열차 이전까지의 최댓값 + dp[i][j] = Integer.max(dp[i][j - 1], dp[i - 1][j - k] + (sum[j] - sum[j - k])); + } + } + + System.out.println(dp[3][n-1]); + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week24/PG_42885.java" "b/src/\352\263\265\354\234\244\355\231\230/week24/PG_42885.java" new file mode 100644 index 0000000..0a2dfb8 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week24/PG_42885.java" @@ -0,0 +1,39 @@ +package d220225; + +import java.util.*; + +/* +프로그래머스42885 구명보트 + +풀이법 : + 1. 최대 2명이 탈 수 있으므로 가장 무거운 사람을 태운 후 가벼운 사람 한 명을 태워봅니다. + + */ + +public class PG_42885 { + + int solution(int[] people, int limit) { + + Arrays.sort(people); // 무게순으로 정렬 + + int heavy = people.length - 1; + int light = 0; + int answer=0; + + while (true) { + int boat = people[heavy]; + + // 자리 남으면 제일 가벼운 사람도 태우기 + if(lightheavy) + break; + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week24/PG_72411.java" "b/src/\352\263\265\354\234\244\355\231\230/week24/PG_72411.java" new file mode 100644 index 0000000..9e8b63d --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week24/PG_72411.java" @@ -0,0 +1,106 @@ +package d220225; + +import java.util.*; + +/* +프로그래머스72411 메뉴 리뉴얼 + +풀이법 : + 1. Map으로 <조합, 주문횟수>를 관리합니다. + 2. 각 손님별로 course[]의 길이들만큼 메뉴조합을 Map에 카운트합니다. + 3. Map에서 course 길이별로 최다 주문된 코스를 리스트에 저장합니다. + + */ + +public class PG_72411 { + + Map menus = new HashMap<>(); // 전체 가능한 조합들 카운트 + String menu; + boolean visited[]; + + List solution(String[] orders, int[] course) { + + // 각 손님별 단품메뉴 조합 + for (String order : orders) { + // 단품 메뉴 갯수별 조합 생성 + for (int len : course) { + menu = ""; + visited = new boolean[order.length()]; + + // 단품메뉴 조합을 알파벳순 정렬 + char[] toChar = order.toCharArray(); + Arrays.sort(toChar); + order = new String(toChar); + + // 단품메뉴 조합에서 len개 조합해서 Map에 카운트 + comb(order, 0, 0, len); + } + } + + return makeAnswer(course); + } + + void comb(String order, int cnt, int start, int len) { + // len개 뽑았으면 Map에 카운트 + if (cnt == len) { + if (!menus.containsKey(menu)) { + menus.put(menu, 0); + } + menus.put(menu, menus.get(menu) + 1); + return; + } + + for (int i = start; i < order.length(); i++) { + if (visited[i]) { + continue; + } + + menu += order.charAt(i); + comb(order, cnt + 1, i + 1, len); + menu = menu.substring(0, menu.length() - 1); + } + } + + // Map에서 갯수별로 최다 주문건 리스트에 추가 + List makeAnswer(int[] course) { + Map max = new HashMap<>(); // len 별 최다 주문횟수 + Map> maxCourse = new HashMap<>(); // 최다 주문횟수의 메뉴 리스트(여러개일수 있음) + List answer = new ArrayList<>(); + + for (int i : course) { + max.put(i, 0); + } + + for (String combination : menus.keySet()) { + int len = combination.length(); + int cnt = menus.get(combination); + int maxCnt = max.get(len); + + // 원하던 길이의 조합이 아니거나 1명만 주문했으면 건너뛰기 + if (!max.containsKey(len) || cnt < 2) { + continue; + } + + // 최다 주문횟수 및 메뉴리스트 갱신 + if (cnt >= maxCnt) { + if (cnt > maxCnt) { + maxCourse.put(len, new ArrayList<>()); + } + + maxCourse.get(len).add(combination); + max.put(len, cnt); + } + } + + for (int key : maxCourse.keySet()) { + List list = maxCourse.get(key); + for (String combination : list) { + answer.add(combination); + } + } + + Collections.sort(answer); + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week25/BJ_1107.java" "b/src/\352\263\265\354\234\244\355\231\230/week25/BJ_1107.java" new file mode 100644 index 0000000..0d9f169 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week25/BJ_1107.java" @@ -0,0 +1,68 @@ +package d220303; + +import java.io.*; +import java.util.*; + +/* +백준1107 리모컨 + +풀이법 : + 1. 타겟 번호 자리수와 +-1 자리수인 수를 dfs로 생성합니다. + 2. 생성한 후 +- 버튼으로 타겟 번호까지 이동해봅니다. + +그냥 0~999999 번호를 다 해보는게 훨씬 효율적이었네요. + */ + + +public class BJ_1107 { + + static String target; + static String trial; + static int answer; + static Set breakdown; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + target = br.readLine(); + breakdown = new HashSet<>(); + answer = Math.abs(100 - Integer.parseInt(target)); + trial = ""; // 시도해볼 번호 + + int n = Integer.parseInt(br.readLine()); + + if (n != 0) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int i = 0; i < n; i++) { + breakdown.add(Integer.parseInt(st.nextToken())); + } + } + + dfs(0); + + System.out.println(answer); + } + + static void dfs(int cnt) { + + // 타겟 번호와 일치하는 자리수 or +-1 자리수인 숫자 도착 + if (cnt < 0 && (cnt == target.length() || cnt == target.length() - 1 + || cnt == target.length() + 1)) { + answer = Integer.min(answer, + Math.abs(Integer.parseInt(trial) - Integer.parseInt(target)) + trial.length()); + + if (cnt == target.length() + 1) { + return; + } + } + + for (int i = 0; i < 10; i++) { + if (breakdown.contains(i)) { + continue; + } + + trial += i; + dfs(cnt + 1); + trial = trial.substring(0, trial.length() - 1); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week25/PG_17684.java" "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_17684.java" new file mode 100644 index 0000000..f281ffc --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_17684.java" @@ -0,0 +1,53 @@ +package d220301; + +import java.util.*; + +/* +프로그래머스17684 압축 + +풀이법 : + 1. Map으로 인덱스를 관리합니다. + 2. 새로운 단어가 나올때까지 인덱스를 늘려가며 단어를 생성합니다. + 3. 새로운 단어는 인덱스를 추가하고 현재 단어 인덱스를 answer에 추가합니다. + + */ + +public class PG_17684 { + + List solution(String msg) { + List answer = new ArrayList<>(); + Map dictionary = new HashMap<>(); + + for (int i = 0; i < 26; i++) { + dictionary.put(new String("" + (char) ('A' + i)), i + 1); + } + + for (int idx = 0; idx < msg.length(); ) { + int len = 1; + if (idx < msg.length()) { + int end = idx; + String existWord = ""; + + // 끝 인덱스 늘려가며 새로운 단어 찾기 + while (++end <= msg.length()) { + String checkWord = msg.substring(idx, end); + if (!dictionary.containsKey(checkWord)) { + dictionary.put(checkWord, dictionary.size() + 1); + idx = end - 1; + break; + } + + existWord = checkWord; + + // 현재 단어가 끝이면 종료 + if (end == msg.length()) { + idx = end; + } + } + + answer.add(dictionary.get(existWord)); + } + } + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week25/PG_42578.java" "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_42578.java" new file mode 100644 index 0000000..84444c3 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_42578.java" @@ -0,0 +1,38 @@ +package d220304; + +import java.util.*; + +/* +프로그래머스42578 위장 + +풀이법 : + 해쉬를 써서 경우의 수를 계산하는 간단한 문제였습니다. + + */ + + +public class PG_42578 { + + public int solution(String[][] clothes) { + int answer = 1; + + HashMap> total = new HashMap<>(); + + for (int i = 0; i < clothes.length; i++) { + String cloth = clothes[i][0]; + String type = clothes[i][1]; + + if (!total.containsKey(type)) { + total.put(type, new HashSet<>()); + } + + total.get(type).add(cloth); + } + + for (String type : total.keySet()) { + answer *= (total.get(type).size() + 1); + } + + return answer - 1; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week25/PG_92343.java" "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_92343.java" new file mode 100644 index 0000000..976a142 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week25/PG_92343.java" @@ -0,0 +1,79 @@ +package d220305; + +import java.util.*; + +/* +프로그래머스92343 양과 늑대 + +풀이법 : + 1. dfs로 탐색을 하며 다음 방문할 수 있는 노드들을 자식들에게 복사해서 넘겨줍니다. + 2. 다음 방문할 노드들 중 자기자신으로 가는 노드는 빼줍니다. + 3. 현재 노드의 양 또는 늑대를 추가해주고 양 최대값을 갱신해줍니다. + 4. 양과 늑대 수가 같은 경우에는 더 진행하지 않고 종료합니다. + +https://velog.io/@hengzizng/프로그래머스-양과-늑대 +참고했습니다. 이해하는데도 오래걸렸네요.. + */ + + +public class PG_92343 { + + static List[] tree; + static int n, answer; + final static int SHEEP = 0; + + public static int solution(int[] info, int[][] edges) { + n = info.length; + tree = new List[n]; + answer = 0; + + for (int i = 0; i < n; i++) { + tree[i] = new ArrayList<>(); + } + + for (int[] edge : edges) { + int from = edge[0]; + int to = edge[1]; + tree[from].add(to); + } + + dfs(0, 0, 0, info, new HashSet()); + + return answer; + } + + static void dfs(int cur, int sheep, int wolf, int[] info, Set next) { + + // 현재 노드 참고해 양 or 늑대 추가 + if (info[cur] == SHEEP) { + sheep++; + } else { + wolf++; + } + + // 양 최대값 갱신 + answer = Math.max(answer, sheep); + + // 지금까지 끌고온 양, 늑대 수가 같다면 종료 + if (sheep == wolf) { + return; + } + + // 다음 방문할 노드 목록에 direct로 연결된 자식들 추가 + for (int child : tree[cur]) { + next.add(child); + } + + // 자신으로 가는 노드는 제거 + next.remove(cur); + + // 자신의 자식 + 부모가 갈 수 있었던 자식들 탐색 + for (int nextNode : next) { + // 방문해볼 노드들 자식에게도 copy해서 넘겨주기 + Set copyNext = new HashSet<>(); + copyNext.addAll(next); + + dfs(nextNode, sheep, wolf, info, copyNext); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/BJ_15684.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/BJ_15684.java" new file mode 100644 index 0000000..cd9211e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/BJ_15684.java" @@ -0,0 +1,113 @@ +package d220313; + +import java.io.*; +import java.util.*; + +/* +백준15684 사다리 조작 + +풀이법 : + 1. 사다리는 2차원 boolean 배열로 관리합니다. + 2. 우선순위큐에서 숫자를 하나씩 빼주고 해당 수 바로 위칸의 수를 다시 넣어줍니다. + 3. 사다리를 0개, 1개, 2개... 순으로 dfs로 뽑아봅니다. + 4. 한번이라도 완성되면 종료합니다. + + */ + + +public class BJ_15684 { + + static int n, m, h, answer; + static boolean[][] ladder; + static int[] dr = {-1, 0, 0}; + static int[] dc = {0, -1, 1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt((st.nextToken())); + h = Integer.parseInt(st.nextToken()); + ladder = new boolean[h][n]; + answer = 4; + + for (int k = 0; k < m; k++) { + st = new StringTokenizer(br.readLine()); + int i = Integer.parseInt(st.nextToken()) - 1; + int j = Integer.parseInt(st.nextToken()) - 1; + ladder[i][j] = true; + } + + for (int i = 0; i < 4; i++) { + // 사다리 i개 놓아보고 체크 + // 가능하면 바로 종료 + if (dfs(0, 0, i)) { + break; + } + } + + System.out.println(answer == 4 ? -1 : answer); + } + + // 사다리를 target개 뽑고 체크 + public static boolean dfs(int cnt, int start, int target) { + + if (cnt == target) { + if (checkLadder()) { + answer = Integer.min(answer, cnt); + return true; + } + + return false; + } + + for (int k = start; k < n * h; k++) { + int i = k / n; + int j = k % n; + + if (j == n - 1 || ladder[i][j] || (j > 0 && ladder[i][j - 1]) || ladder[i][j + + 1]) { + continue; + } + + ladder[i][j] = true; + + // 한 번이라도 성공하면 종료 + if (dfs(cnt + 1, k + 1, target)) { + return true; + } + + ladder[i][j] = false; + } + + return false; + } + + public static boolean checkLadder() { + + int i, j; + + for (int l = 0; l < n; l++) { + i = 0; + j = l; + + while (i != h) { + + if (j > 0 && ladder[i][j - 1]) { + j = j - 1; + } else if (ladder[i][j]) { + j = j + 1; + } + + i++; + } + + if (j != l) { + return false; + } + } + + return true; + } +} \ No newline at end of file diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/BJ_2075.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/BJ_2075.java" new file mode 100644 index 0000000..ec5a7d3 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/BJ_2075.java" @@ -0,0 +1,68 @@ +package d220311; + +import java.io.*; +import java.util.*; + +/* +백준2075 N번째 큰 수 + +풀이법 : + 1. 제일 아래줄 숫자들을 우선순위큐에 넣어줍니다. + 2. 우선순위큐에서 숫자를 하나씩 빼주고 해당 수 바로 위칸의 수를 다시 넣어줍니다. + + */ + +public class BJ_2075 { + + static int n, board[][]; + + static class Number { + + int i; + int j; + int number; + + Number(int i, int j, int number) { + this.i = i; + this.j = j; + this.number = number; + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + board = new int[n][n]; + // 내림차순 정렬 + PriorityQueue pq = new PriorityQueue<>( + (o1, o2) -> Integer.compare(o2.number, o1.number)); + + int answer = 0; + int cnt = 0; + + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + board[i][j] = Integer.parseInt(st.nextToken()); + + if (i == n - 1) { + pq.offer(new Number(i, j, board[i][j])); + } + } + } + + while (!pq.isEmpty()) { + Number num = pq.poll(); + answer = num.number; + cnt++; + + if (num.i >0) { + pq.offer(new Number(num.i - 1, num.j, board[num.i - 1][num.j])); + } + + if(cnt==n) + break; + } + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/PG_42626.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_42626.java" new file mode 100644 index 0000000..251e047 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_42626.java" @@ -0,0 +1,47 @@ +package d220312; + +import java.util.*; + +/* +프로그래머스42626 더 맵게 + +풀이법 : + PriorityQueue 사용 + + */ + +public class PG_42626 { + + public static void main(String[] args) { + System.out.println(solution(new int[]{1, 2, 3, 9, 10, 12}, 7)); + } + + public static int solution(int[] scoville, int K) { + int answer = 0; + PriorityQueue pq = new PriorityQueue<>(); + + for (int s : scoville) { + pq.offer(s); + } + + while (true) { + int first = pq.poll(); + + if(first>= K){ + return answer; + } + + if(pq.isEmpty()) + return -1; + + int second = pq.poll(); + + if (first == 0 && second == 0) { + return -1; + } + + pq.offer(first + second*2); + answer++; + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/PG_92342.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_92342.java" new file mode 100644 index 0000000..020f489 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_92342.java" @@ -0,0 +1,88 @@ +package d220312; + +/* +프로그래머스92342 양궁대회 + +풀이법 : + 1. dfs로 해당 점수 과녁을 맞추기 or 안맞추기로 분기해나갑니다. + 2. 화살은 항상 어피치+1 만큼 맞추고 화살이 부족하면 그냥 넘어갑니다. + 3. 0점까지 갔을 때 남은 화살은 0점에 몰아줍니다. + + */ + + +public class PG_92342 { + + int[] shoot = new int[11]; + int n, max; + int[] apeachShoot, answer; + boolean flag; + + public int[] solution(int N, int[] info) { + answer = new int[11]; + n = N; + apeachShoot = info; + max = 1; + flag = false; + + dfs(0, 0); + + return flag ? answer : new int[]{-1}; + } + + public void dfs(int cnt, int arrow) { + // 모든 점수 과녁 체크 완료 + if (cnt == 11) { + shoot[10] = n - arrow; // 남은 화살은 0점에 + + int lionScore = 0; + int apeachScore = 0; + + // 점수 계산 + for (int i = 0; i < 11; i++) { + if (shoot[i] == 0 && apeachShoot[i] == 0) { + continue; + } + lionScore += shoot[i] > apeachShoot[i] ? 10 - i : 0; + apeachScore += shoot[i] <= apeachShoot[i] ? 10 - i : 0; + } + + if (lionScore - apeachScore >= max) { + flag = true; + + // max 값이 동률일 때 우선순위 계산 + if (lionScore - apeachScore == max) { + for (int i = 10; i >= 0; i--) { + if (answer[i] == shoot[i]) { + continue; + } + + answer = answer[i] > shoot[i] ? answer : shoot.clone(); + break; + } + } + + // 그냥 max 값 새로 갱신 + else { + max = lionScore - apeachScore; + answer = shoot.clone(); + } + } + + return; + } + + // 어피치보다 1개 더 맞춰야함 + int mustShoot = apeachShoot[cnt] + 1; + + // 화살 갯수 남았을 때만 과녁 선택하기 + if (arrow + mustShoot <= n) { + shoot[cnt] = mustShoot; + dfs(cnt + 1, arrow + mustShoot); + shoot[cnt] = 0; + } + + // 해당 점수는 안맞추고 넘어가기 + dfs(cnt + 1, arrow); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/PG_92344.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_92344.java" new file mode 100644 index 0000000..f781746 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/PG_92344.java" @@ -0,0 +1,90 @@ +package d220309; + +/* +프로그래머스92344 파괴되지 않은 건물 + +풀이법 : + 1. skill 값들을 누적합으로 기록해둡니다. + 2. 누적합 기록으로 전체 건물 변화량을 계산합니다. + 3. board와 변화량으로 파괴되지 않은 건물을 카운트합니다. + + */ + + +public class PG_92344 { + + public static int solution(int[][] board, int[][] skills) { + int answer = 0; + int n = board.length; + int m = board[0].length; + int[][] sum = new int[n][m]; // skill 누적합 + int[][] skillAmount; // 각 칸별 변화량 + + for (int[] skill : skills) { + int type = skill[0]; + int r1 = skill[1]; + int c1 = skill[2]; + int r2 = skill[3]; + int c2 = skill[4]; + int degree = type == 1 ? -skill[5] : skill[5]; // 파괴이면 - 해주기 + + sum[r2][c2] += degree; // (0, 0) ~ (r2, c2) 누적합 + + // 왼쪽 누적합 빼주기 + if (c1 > 0) { + sum[r2][c1 - 1] -= degree; + } + + //위쪽 누적합 빼주기 + if (r1 > 0) { + sum[r1 - 1][c2] -= degree; + } + + // 중복으로 빠진 좌상단 누적합 다시 더해주기 + if (c1 > 0 && r1 > 0) { + sum[r1 - 1][c1 - 1] += degree; + } + } + + skillAmount = calcAmount(sum); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (board[i][j] + skillAmount[i][j] > 0) { + answer++; + } + } + } + + return answer; + } + + static int[][] calcAmount(int[][] sum) { + + int n = sum.length; + int m = sum[0].length; + + int[][] amount = new int[n][m]; + + // 행별로 우 -> 좌 누적합 계산 + for (int i = n - 1; i >= 0; i--) { + int tmp = 0; + for (int j = m - 1; j >= 0; j--) { + tmp += sum[i][j]; + amount[i][j] += tmp; + } + } + + // 열별로 하 -> 상 누적합 계산 + for (int j = m - 1; j >= 0; j--) { + int tmp = 0; + + for (int i = n - 1; i >= 0; i--) { + amount[i][j] += tmp; + tmp = amount[i][j]; + } + } + + return amount; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Four.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Four.java" new file mode 100644 index 0000000..2fcb3aa --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Four.java" @@ -0,0 +1,68 @@ +package SK; + +import java.util.*; + +public class Four { + + public static void main(String[] args) { + System.out.println(solution(5, new int[][]{{0, 1}, {0, 2}, {1, 3}, {1, 4}})); + System.out.println(solution(4, new int[][]{{0, 1}, {1, 2},{2,3}})); + } + + static List[] graph; + static boolean visited[]; + static int N, root; + static long answer; + + public static long solution(int n, int[][] edges) { + answer = 0; + N = n; + graph = new List[N]; + for (int i = 0; i < N; i++) { + graph[i] = new ArrayList<>(); + } + + for (int[] edge : edges) { + int from = edge[0]; + int to = edge[1]; + + graph[from].add(to); + graph[to].add(from); + } + + for (int i = 0; i < N; i++) { + root = i; + visited = new boolean[N]; + dfs(i, false); + } + + return answer; + } + + static void dfs(int cur, boolean via) { + if (visited[cur]) { + return; + } + + visited[cur] = true; + + for (int next : graph[cur]) { + + if (cur == root) { + dfs(next, false); + continue; + } + + if (!via) { + dfs(next, true); + dfs(next, false); + continue; + } + + if (via) { + dfs(next, true); + answer++; + } + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/One.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/One.java" new file mode 100644 index 0000000..d96728b --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/One.java" @@ -0,0 +1,34 @@ +package SK; + +import java.util.*; + +public class One { + + public static void main(String[] args) { + System.out.println(solution(4578, new int[]{1, 4, 99, 35, 50, 1000})); + } + + public static int solution(int money, int[] costs) { + int[] won = {1, 5, 10, 50, 100, 500}; + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Double.compare(o1[1], o2[1])); + int answer = 0; + + for (int i = 0; i < costs.length; i++) { + pq.offer(new double[]{i, (double) costs[i] / won[i]}); + } + + while(!pq.isEmpty()){ + if(money==0) + break; + + int produce = 0; + int idx = (int)pq.poll()[0]; + + produce = money/won[idx]; + answer+=produce*costs[idx]; + money-=produce*won[idx]; + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Three.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Three.java" new file mode 100644 index 0000000..3376322 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Three.java" @@ -0,0 +1,59 @@ +package SK; + +public class Three { + + public static void main(String[] args) { + System.out.println(solution(51, 37, new int[][]{{17,19}})); + } + + static final int MOD = 10000019; + + public static int solution(int width, int height, int[][] diagonals) { + int[][] dp = new int[height + 1][width + 1]; + int answer = 0; + + for (int i = 0; i < height + 1; i++) { + dp[i][0] = 1; + } + + for (int j = 0; j < width + 1; j++) { + dp[0][j] = 1; + } + + for (int i = 1; i < height + 1; i++) { + for (int j = 1; j < width + 1; j++) { + dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD; + } + } + + for (int[] diagonal : diagonals) { + int[][] tmp = new int[height + 1][width + 1]; + + int leftR = diagonal[1]; + int leftC = diagonal[0] - 1; + int rightR = diagonal[1] - 1; + int rightC = diagonal[0]; + + tmp[leftR][leftC] = dp[rightR][rightC]; + tmp[rightR][rightC] = dp[leftR][leftC]; + + for (int i = leftR + 1; i < height + 1; i++) { + tmp[i][leftC] = tmp[leftR][leftC]; + } + + for (int j = rightC + 1; j < width + 1; j++) { + tmp[rightR][j] = tmp[rightR][rightC]; + } + + for (int i = leftR; i < height + 1; i++) { + for (int j = rightC; j < width + 1; j++) { + tmp[i][j] = (tmp[i - 1][j] + tmp[i][j - 1]) % MOD; + } + } + + answer += tmp[height][width] % MOD; + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Two.java" "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Two.java" new file mode 100644 index 0000000..b06da6e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week26/SK_ICT/Two.java" @@ -0,0 +1,55 @@ +package SK; + +import java.util.Arrays; + +public class Two { + + public static void main(String[] args) { + solution(1000, false); +// solution(6, false); + } + + public static int[][] solution(int n, boolean clockwise) { + int[][] answer = new int[n][n]; + int level = 0; + int num = 1; + + while (true) { + int start = num; + int i = level; + int j = level; + + for (int k = 0; k < n - 2 * level - 1; k++) { + if (clockwise) { + answer[i][j + k] = answer[i + k][n - 1 - level] = answer[n - 1 - level][n - 1 + - level - k] = answer[n - 1 - level - k][j] = start++; + } else { + answer[i + k][j] = answer[n - 1 - level][j + k] = answer[n - 1 - level - k][n + - 1 + - level] = answer[i][n - 1 - level - k] = start++; + } + } + if (n % 2 == 1) { + answer[level][level] = num; + } + + level++; + + if (level >= (n + 1) / 2) { + break; + } + + if (clockwise) { + num = answer[level][level - 1] + 1; + } else { + num = answer[level - 1][level] + 1; + } + } + + for (int[] p : answer) { + System.out.println(Arrays.toString(p)); + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week27/BJ_10026.java" "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_10026.java" new file mode 100644 index 0000000..a6e0721 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_10026.java" @@ -0,0 +1,84 @@ +package d220319; + +import java.io.*; + +/* +백준10026 + +풀이법 : + 1. 적록색약의 경우 'G'를 'R'로 치환해 배열을 하나더 선언합니다. + 2. dfs로 영역 카운트 + + */ + +public class BJ_10026 { + + static int n, area; + static char[][] map, colorBlind; + static boolean visited[][]; + static int[] dr = {-1, 1, 0, 0}; + static int[] dc = {0, 0, -1, 1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + map = new char[n][n]; + colorBlind = new char[n][n]; + + for (int i = 0; i < n; i++) { + char[] input = br.readLine().toCharArray(); + + for (int j = 0; j < n; j++) { + map[i][j] = colorBlind[i][j] = input[j]; + + if (colorBlind[i][j] == 'G') { + colorBlind[i][j] = 'R'; + } + } + } + + area = 0; + visited = new boolean[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (!visited[i][j]) { + dfs(i, j, map); + area++; + } + } + } + + System.out.print(area+" "); + + area = 0; + visited = new boolean[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (!visited[i][j]) { + dfs(i, j, colorBlind); + area++; + } + } + } + + System.out.println(area); + } + + static void dfs(int i, int j, char[][] target) { + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n || visited[nr][nc] + || target[i][j] != target[nr][nc]) { + continue; + } + + visited[nr][nc] = true; + dfs(nr, nc, target); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week27/BJ_1012.java" "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_1012.java" new file mode 100644 index 0000000..3b1217a --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_1012.java" @@ -0,0 +1,61 @@ +package d220319; + +import java.util.*; +import java.io.*; + +public class BJ_1012 { + + static int[] dr = new int[]{-1, 1, 0, 0}; + static int[] dc = new int[]{0, 0, -1, 1}; + static int m, n; + static boolean[][] visited; + static int[][] map; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int testcase = Integer.parseInt(br.readLine()); + + for (int t = 0; t < testcase; t++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + m = Integer.parseInt(st.nextToken()); + n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + map = new int[m][n]; + visited = new boolean[m][n]; + int answer = 0; + + for (int i = 0; i < k; i++) { + st = new StringTokenizer(br.readLine()); + map[Integer.parseInt(st.nextToken())][Integer.parseInt( + st.nextToken())] = 1; + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j]==1 && !visited[i][j]) { + answer++; + dfs(i, j); + } + } + } + + System.out.println(answer); + } + } + + static void dfs(int i, int j) { + + visited[i][j] = true; + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr <0 || nc < 0 || nr == m || nc == n || visited[nr][nc] || map[nr][nc]!=1) { + continue; + } + + dfs(nr, nc); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week27/BJ_14501.java" "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_14501.java" new file mode 100644 index 0000000..8228e48 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_14501.java" @@ -0,0 +1,44 @@ +package d220318; + +import java.io.*; +import java.util.StringTokenizer; + +public class BJ_14501 { + + static int[][] schedule; + static int answer, n; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + schedule = new int[n + 1][2]; + answer = 0; + + for (int i = 1; i <= n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + schedule[i][0] = Integer.parseInt(st.nextToken()); + schedule[i][1] = Integer.parseInt(st.nextToken()); + } + + dfs(1, 0, 0); + + System.out.println(answer); + } + + static void dfs(int start, int cost, int profit) { + + if (start > n + 1) { + answer = Math.max(answer, profit); + return; + } + + if(start==n+1){ + answer = Math.max(answer, profit+cost); + return; + } + + for (int i = start; i <= n; i++) { + dfs(i + schedule[i][0], schedule[i][1], profit+cost); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week27/BJ_2473.java" "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_2473.java" new file mode 100644 index 0000000..4c4e318 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_2473.java" @@ -0,0 +1,63 @@ +package d220321; + +import java.io.*; +import java.util.*; + +/* +백준2473 세 용액 + +풀이법 : + 1. 브루트포스 + 투포인터 + 2. 왼쪽 부터 하나 선택합니다. + 3. 왼쪽+1 ~ 끝 중에서 투포인터로 최소 값을 가지는 용액 2개를 고릅니다. + 4. 왼쪽을 하나 증가시키고 똑같은 작업을 반복합니다. + + */ + +public class BJ_2473 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + StringTokenizer st = new StringTokenizer(br.readLine()); + long[] liquid = new long[n]; + long[] answer = new long[3]; + long min = Long.MAX_VALUE; + + for(int i=0;i 0) { + third--; + } else if(sum<0) { + second++; + }else{ + break; + } + } + } + + for(long a: answer){ + System.out.print(a+" "); + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week27/BJ_5567.java" "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_5567.java" new file mode 100644 index 0000000..29f6605 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week27/BJ_5567.java" @@ -0,0 +1,56 @@ +package d220321; + +import java.util.*; +import java.io.*; + +// BFS 탐색 + +public class BJ_5567 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + int m = Integer.parseInt(br.readLine()); + List[] friends = new List[n + 1]; + Queue q = new ArrayDeque<>(); + boolean[] visited = new boolean[n + 1]; + int answer = 0; + + for (int i = 1; i <= n; i++) { + friends[i] = new ArrayList<>(); + } + + for (int i = 0; i < m; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + friends[from].add(to); + friends[to].add(from); + } + + q.add(1); + visited[1] = true; + int cnt = 0; + + while (!q.isEmpty() && cnt < 3) { + int size = q.size(); + while (size-- > 0) { + int cur = q.poll(); + answer++; + + for (int friend : friends[cur]) { + if (visited[friend]) { + continue; + } + + visited[friend] = true; + q.offer(friend); + } + } + cnt++; + } + + System.out.println(answer-1); + + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week28/BJ_11003.java" "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_11003.java" new file mode 100644 index 0000000..7574e47 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_11003.java" @@ -0,0 +1,41 @@ +package d220325; + +import java.util.*; +import java.io.*; + +public class BJ_11003 { + + static class Num { + + int num; + int idx; + + Num(int num, int idx) { + this.num = num; + this.idx = idx; + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + StringBuilder sb = new StringBuilder(); + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1.num, o2.num)); + + int n = Integer.parseInt(st.nextToken()); + int l = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + + for (int i = 0; i < n; i++) { + pq.offer(new Num(Integer.parseInt(st.nextToken()), i)); + + while (pq.peek().idx < i - l + 1) { + pq.poll(); + } + + sb.append(pq.peek().num+" "); + } + + System.out.println(sb); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week28/BJ_1890.java" "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_1890.java" new file mode 100644 index 0000000..e2ad06e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_1890.java" @@ -0,0 +1,56 @@ +package d220325; + +import java.util.*; +import java.io.*; + +public class BJ_1890 { + + static int n, map[][]; + static long answer; + static long dp[][]; + static boolean visited[][]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + map = new int[n][n]; + dp = new long[n][n]; + visited = new boolean[n][n]; + + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + + dfs(0, 0); + System.out.println(dp[0][0]); + } + + public static long dfs(int i, int j) { + + if (i == n - 1 && j == n - 1) { + return 1; + } + + if (map[i][j] == 0) { + return 0; + } + + if (i + map[i][j] < n && visited[i + map[i][j]][j]) { + dp[i][j] += dp[i + map[i][j]][j]; + } else if (i + map[i][j] < n) { + dp[i][j] += dfs(i + map[i][j], j); + } + + if (j + map[i][j] < n && visited[i][j + map[i][j]]) { + dp[i][j] += dp[i][j + map[i][j]]; + } else if (j + map[i][j] < n) { + dp[i][j] += dfs(i, j + map[i][j]); + } + + visited[i][j] = true; + return dp[i][j]; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week28/BJ_21610.java" "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_21610.java" new file mode 100644 index 0000000..3932d9b --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week28/BJ_21610.java" @@ -0,0 +1,114 @@ +package d220325; + +import java.util.*; +import java.io.*; + +public class BJ_21610 { + + static int n, m, map[][], tmpMap[][]; + static List cloudPos; + static boolean[][] prevCloud; + static int[] dr = {0, 0, -1, -1, -1, 0, 1, 1, 1}; + static int[] dc = {0, -1, -1, 0, 1, 1, 1, 0, -1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + map = new int[n][n]; + tmpMap = new int[n][n]; + prevCloud = new boolean[n][n]; + cloudPos = new ArrayList<>(); + + cloudPos.add(new int[]{n - 1, 0}); + cloudPos.add(new int[]{n - 1, 1}); + cloudPos.add(new int[]{n - 2, 0}); + cloudPos.add(new int[]{n - 2, 1}); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int d = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + + moveAndRain(d, s); + waterBug(); + makeCloud(); + } + + System.out.println(calcSum()); + } + + static void moveAndRain(int d, int s) { + for (int[] pos : cloudPos) { + for (int i = 0; i < s; i++) { + pos[0] = (n + pos[0] + dr[d]) % n; + pos[1] = (n + pos[1] + dc[d]) % n; + } + + map[pos[0]][pos[1]]++; + prevCloud[pos[0]][pos[1]] = true; + } + } + + static void waterBug() { + for (int[] pos : cloudPos) { + for (int d = 2; d <= 8; d += 2) { + + int nr = pos[0] + dr[d]; + int nc = pos[1] + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n) { + continue; + } + + if (map[nr][nc] > 0) { + tmpMap[pos[0]][pos[1]]++; + } + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j] += tmpMap[i][j]; + tmpMap[i][j] = 0; + } + } + } + + public static void makeCloud() { + cloudPos.clear(); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j] >= 2 && !prevCloud[i][j]) { + map[i][j] -= 2; + cloudPos.add(new int[]{i, j}); + } + + if (prevCloud[i][j]) { + prevCloud[i][j] = false; + } + } + } + } + + public static int calcSum() { + int answer = 0; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + answer += map[i][j]; + } + } + + return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week29/BJ_1654.java" "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_1654.java" new file mode 100644 index 0000000..0ece987 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_1654.java" @@ -0,0 +1,43 @@ +package d220329; + +import java.io.*; +import java.util.*; + +public class BJ_1654 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int k = Integer.parseInt(st.nextToken()); + int n = Integer.parseInt(st.nextToken()); + int answer = 0; + int[] lan = new int[k]; + + for (int i = 0; i < k; i++) { + lan[i] = Integer.parseInt(br.readLine()); + } + + Arrays.sort(lan); + + long left = 1; + long right = lan[k - 1]; + + while (left <= right) { + long mid = (left + right) / 2; + int tmp = 0; + + for (int i = 0; i < k; i++) { + tmp += lan[i] / mid; + } + + if (tmp < n) { + right = mid - 1; + } else { + answer = (int)mid; + left = mid + 1; + } + } + + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week29/BJ_20056.java" "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_20056.java" new file mode 100644 index 0000000..387fb20 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_20056.java" @@ -0,0 +1,189 @@ +package d220330; + +import java.io.*; +import java.util.*; + +/* +백준20056 마법사 상어와 파이어볼 + +풀이법 : + 1. 파이어볼 하나의 정보인 FireBall과 map의 각 칸별 파이어볼들 정보를 담는 FireBallInfo를 사용합니다. + 2. Step1 각 칸의 FireBallInfo에 있는 큐에서 FireBall들을 이동시킵니다. + 3. Step2 각 칸별 FireBallInfo에서 파이어볼이 2개 이상이면 2단계 작업을 수행합니다. + 4. 각 칸별 FireBallInfo에서 현재 몇개가 있는지 cnt를 갱신합니다. + + */ + +public class BJ_20056 { + + static int n; + static FireBallInfo[][] map; + static int[] dr = {-1, -1, 0, 1, 1, 1, 0, -1}; + static int[] dc = {0, 1, 1, 1, 0, -1, -1, -1}; + + // FireBall 하나 + static class FireBall { + + int mass; + int speed; + int dir; + + FireBall(int mass, int speed, int dir) { + this.mass = mass; + this.speed = speed; + this.dir = dir; + } + } + + // map[i][j]의 FireBall들 정보 + static class FireBallInfo { + + int cnt; + Queue q; + + FireBallInfo() { + q = new ArrayDeque<>(); + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + int m = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + map = new FireBallInfo[n][n]; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j] = new FireBallInfo(); + } + } + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int r = Integer.parseInt(st.nextToken()) - 1; + int c = Integer.parseInt(st.nextToken()) - 1; + int mass = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + int d = Integer.parseInt(st.nextToken()); + + map[r][c].q.add(new FireBall(mass, s, d)); + } + + // 각 칸별 FireBallInfo에 현재 파이어볼 몇개인지 초기화 + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j].cnt = map[i][j].q.size(); + } + } + + for (int i = 0; i < k; i++) { + move(); + mergeAndSplit(); + setCnt(); + } + + System.out.println(calc()); + } + + // move: 각 칸의 FireBall 큐에서 기존에 있던 파이어볼들만 이동시키기 + static void move() { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j].cnt == 0) { + continue; + } + + Queue q = map[i][j].q; + int cnt = map[i][j].cnt; // 원래 칸에 있던 파이어볼 개수 + + for (int k = 0; k < cnt; k++) { + FireBall fb = q.poll(); + int nr = (i + dr[fb.dir] * fb.speed) % n; + int nc = (j + dc[fb.dir] * fb.speed) % n; + if (nr < 0) { + nr += n; + } + if (nc < 0) { + nc += n; + } + + map[nr][nc].q.add(fb); // 새로운 위치로 파이어볼 이동 + } + } + } + } + + // mergeAndSplit: 2개 이상이면 합치고 쪼개기 + static void mergeAndSplit() { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j].cnt = map[i][j].q.size(); + + if (map[i][j].cnt < 2) { + continue; + } + + Queue q = map[i][j].q; + int cnt = q.size(); + int newM = 0; + int newS = 0; + int newD = q.peek().dir % 2; // 첫 번째 파이어볼 방향 + boolean sameD = true; + + while (!q.isEmpty()) { + FireBall fb = q.poll(); + newM += fb.mass; + newS += fb.speed; + + // 방향 하나라도 다르면 false + if (fb.dir % 2 != newD) { + sameD = false; + } + } + + newM /= 5; + newS /= cnt; + newD = sameD ? 0 : 1; + + // 파이어볼 소멸 + if (newM == 0) { + continue; + } + + // 4개로 쪼개진 파이어볼 추가 + for (int k = 0; k < 4; k++) { + map[i][j].q.add(new FireBall(newM, newS, newD)); + newD += 2; + } + } + } + } + + // map의 각 칸의 FireBallInfo에 FireBall 몇개인지 cnt 갱신 + static void setCnt() { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j].cnt = map[i][j].q.size(); + } + } + } + + static int calc() { + int mass = 0; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + Queue q = map[i][j].q; + + while (!q.isEmpty()) { + FireBall fb = q.poll(); + mass += fb.mass; + } + } + } + + return mass; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week29/BJ_2206.java" "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_2206.java" new file mode 100644 index 0000000..fd5291e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week29/BJ_2206.java" @@ -0,0 +1,65 @@ +package d220402; + +import java.util.*; +import java.io.*; + +public class BJ_2206 { + + static int n, m, answer, map[][]; + static boolean visited[][][]; + static int dr[] = {-1, 1, 0, 0}; + static int dc[] = {0, 0, -1, 1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + map = new int[n][m]; + visited = new boolean[n][m][2]; + answer = -1; + Queue q = new ArrayDeque<>(); + + for (int i = 0; i < n; i++) { + String[] input = br.readLine().split(""); + for (int j = 0; j < m; j++) { + map[i][j] = Integer.parseInt(input[j]); + } + } + + q.offer(new int[]{0, 0, 1, 0}); + visited[0][0][0] = true; + + while (!q.isEmpty()) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + int len = cur[2]; + int breakCnt = cur[3]; + + if (r == n - 1 && c == m - 1) { + answer = len; + break; + } + + for (int d = 0; d < 4; d++) { + int nr = r + dr[d]; + int nc = c + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == m) { + continue; + } + + if (map[nr][nc] == 0 && !visited[nr][nc][breakCnt]) { + visited[nr][nc][breakCnt] = true; + q.offer(new int[]{nr, nc, len + 1, breakCnt}); + } else if (map[nr][nc] == 1 && breakCnt == 0 && !visited[nr][nc][1]) { + visited[nr][nc][1] = true; + q.offer(new int[]{nr, nc, len + 1, 1}); + } + } + } + + System.out.println(answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week29/PG_12920.java" "b/src/\352\263\265\354\234\244\355\231\230/week29/PG_12920.java" new file mode 100644 index 0000000..62af64e --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week29/PG_12920.java" @@ -0,0 +1,88 @@ +package d220331; + +/* +프로그래머스12920 선입 선출 스케줄링 + +풀이법 : + 1. 작업 처리 시간을 이분탐색으로 하여 n개 수행 여부를 체크합니다. + 2. 해당 작업 시간까지 프로세스를 n개 이상 했다면 해당 시간에 추가했던 작업들을 뒤에서부터 빼주며 n개가 되는 지점을 찾습니다. + +우선순위큐를 쓰면 터지는 악질 문제... + */ + + +public class PG_12920 { + + public int solution(int n, int[] cores) { + + int answer = 0; + + if (n <= cores.length) { + return n; + } + + int left = 0; + int right = cores[0] * n; + + while (left <= right) { + int mid = (left + right) / 2; + int totalProcess = 0; + + // mid 시간까지 core에 올라간 작업 수 + // mid 시간이 작업 시간으로 나누어 떨어질 때 추가할 수 있다. + for (int core : cores) { + totalProcess += mid / core + 1; + } + + if (totalProcess < n) { + left = mid + 1; + } + + // 총 작업량이 n개 이상이면 total이 n개가 될 때까지 추가했던 작업을 뒤에서부터 빼본다. + else { + for (int i = cores.length - 1; i >= 0; i--) { + int core = cores[i]; + + if (mid % core == 0) { + if (totalProcess == n) { + return i + 1; + } + + totalProcess--; + } + } + + right = mid - 1; + } + } + + return answer; + +// int answer = 0; +// int time = 0; +// +// PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { +// if (o1[0] != o2[0]) { +// return Integer.compare(o1[0], o2[0]); +// } +// return Integer.compare(o1[1], o2[1]); +// }); +// +// for (int i = 0; i < cores.length; i++) { +// pq.offer(new int[]{cores[i], i + 1}); +// n--; +// } +// +// while (n-- > 0) { +// int[] cur = pq.poll(); +// time = cur[0]; +// int emptyCore = cur[1]; +// int processTime = cores[emptyCore - 1]; +// +// answer = emptyCore; +// +// pq.offer(new int[]{time + processTime, emptyCore}); +// } +// return answer; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week30/BG_16235.java" "b/src/\352\263\265\354\234\244\355\231\230/week30/BG_16235.java" new file mode 100644 index 0000000..73e905a --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week30/BG_16235.java" @@ -0,0 +1,168 @@ +package d220410; + +import java.util.*; +import java.io.*; + +/* +백준16235 나무 제태크 + +풀이법 : + 시뮬레이션 + + */ + +public class BG_16235 { + + static int nutrient[][], n, m, k; + static Land[][] map; + static int[] dr = {-1, -1, -1, 0, 0, 1, 1, 1,}; + static int[] dc = {-1, 0, 1, -1, 1, -1, 0, 1}; + + static class Land { + + int nutrient; + PriorityQueue trees; + Queue dead; + + Land(int nutrient) { + this.nutrient = nutrient; + trees = new PriorityQueue<>(); + dead = new ArrayDeque<>(); + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + k = Integer.parseInt(st.nextToken()); + nutrient = new int[n][n]; + map = new Land[n][n]; + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine(), " "); + for (int j = 0; j < n; j++) { + nutrient[i][j] = Integer.parseInt(st.nextToken()); + map[i][j] = new Land(5); + } + } + + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + int r = Integer.parseInt(st.nextToken()) - 1; + int c = Integer.parseInt(st.nextToken()) - 1; + int age = Integer.parseInt(st.nextToken()); + map[r][c].trees.offer(age); + } + + for (int i = 0; i < k; i++) { + spring(); + summer(); + fall(); + winter(); + } + + System.out.println(answer()); + } + + static void spring() { + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j].trees.size() == 0) { + continue; + } + + Land land = map[i][j]; + int size = land.trees.size(); + Queue grow = new ArrayDeque<>(); + + while (size-- > 0) { + int tree = land.trees.poll(); + + if (tree > land.nutrient) { + land.dead.offer(tree); + continue; + } + + land.nutrient -= tree; + grow.offer(tree + 1); + } + + while (!grow.isEmpty()) { + land.trees.offer(grow.poll()); + } + } + } + } + + static void summer() { + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j].dead.size() == 0) { + continue; + } + + Queue dead = map[i][j].dead; + + while (!dead.isEmpty()) { + int deadTree = dead.poll(); + map[i][j].nutrient += deadTree / 2; + } + } + } + } + + static void fall() { + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (map[i][j].trees.size() == 0) { + continue; + } + + Land land = map[i][j]; + + for (int tree : land.trees) { + if (tree % 5 != 0) { + continue; + } + + for (int d = 0; d < 8; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n) { + continue; + } + + map[nr][nc].trees.offer(1); + } + } + } + } + } + + static void winter() { + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + map[i][j].nutrient += nutrient[i][j]; + } + } + } + + static int answer() { + int cnt = 0; + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + cnt += map[i][j].trees.size(); + } + } + + return cnt; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week30/BJ_14889.java" "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_14889.java" new file mode 100644 index 0000000..4a80e16 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_14889.java" @@ -0,0 +1,69 @@ +package d220407; + +import java.util.*; +import java.io.*; + +public class BJ_14889 { + + static int n, answer, map[][]; + static boolean member[]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + answer = Integer.MAX_VALUE; + map = new int[n][n]; + member = new boolean[n]; + + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + + makeTeam(0, 0); + + System.out.println(answer); + } + + static void makeTeam(int cnt, int start) { + if (cnt == n / 2) { + calc(); + return; + } + + for (int i = start; i < n; i++) { + member[i] = true; + makeTeam(cnt + 1, i + 1); + member[i] = false; + } + } + + static void calc() { + int score1; + int score2; + score1 = score2 = 0; + + for (int i = 0; i < n; i++) { + boolean team = member[i]; + int score = 0; + + for (int j = 0; j < n; j++) { + if (i == j || member[j] != team) { + continue; + } + + score += map[i][j]; + } + + if (team) { + score1 += score; + } else { + score2 += score; + } + } + + answer = Integer.min(Math.abs(score1 - score2), answer); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week30/BJ_16946.java" "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_16946.java" new file mode 100644 index 0000000..a0eada1 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_16946.java" @@ -0,0 +1,95 @@ +package d220407; + +import java.util.*; +import java.io.*; + +public class BJ_16946 { + + static int n, m, map[][]; + static boolean visited[][]; + static int[] dr = new int[]{-1, 1, 0, 0}; + static int[] dc = new int[]{0, 0, -1, 1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + StringBuilder sb = new StringBuilder(); + + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + map = new int[n][m]; + visited = new boolean[n][m]; + + int num = 2; + Map count = new HashMap<>(); + + for (int i = 0; i < n; i++) { + String[] input = br.readLine().split(""); + for (int j = 0; j < m; j++) { + map[i][j] = Integer.parseInt(input[j]); + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (map[i][j] == 1 || visited[i][j]) { + continue; + } + + int cnt = dfs(i, j, num); + count.put(num++, cnt); + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (map[i][j] != 1) { + sb.append(0); + continue; + } + + int tmp = 0; + Set set = new HashSet<>(); + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == m || map[nr][nc] == 1 || set.contains( + map[nr][nc])) { + continue; + } + + set.add(map[nr][nc]); + tmp += count.get(map[nr][nc]); + } + + sb.append((tmp + 1) % 10); + } + + sb.append("\n"); + } + + System.out.println(sb); + } + + static int dfs(int i, int j, int num) { + + int cnt = 1; + visited[i][j] = true; + map[i][j] = num; + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == m || visited[nr][nc] || map[nr][nc] == 1) { + continue; + } + + cnt += dfs(nr, nc, num); + } + + return cnt; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week30/BJ_4991.java" "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_4991.java" new file mode 100644 index 0000000..583c451 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week30/BJ_4991.java" @@ -0,0 +1,160 @@ +package d220411; + +import java.util.*; +import java.io.*; + +/* +백준4991 로봇 청소기 + +풀이법 : + 1. 시작점과 더러운 칸 사이의 모든 최소 거리들을 계산해둡니다. + 2. 완전탐색으로 더러운 칸을 방문하는 모든 순서쌍을 구하고 최솟값을 갱신합니다. + 3. 한번이라도 다음칸으로 못가는 순서쌍이 나오면 -1을 출력합니다. + + */ + +public class BJ_4991 { + + static int w, h, dirty, answer, order[], distance[][]; + static char[][] map; + static boolean[] used; + static List dirtyPos; + static int[] startPos; + static int[] dr = {-1, 1, 0, 0}; + static int[] dc = {0, 0, -1, 1}; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + + while (true) { + StringTokenizer st = new StringTokenizer(br.readLine(), " "); + w = Integer.parseInt(st.nextToken()); + h = Integer.parseInt(st.nextToken()); + dirtyPos = new ArrayList<>(); + dirty = 0; + answer = Integer.MAX_VALUE; + map = new char[h][w]; + + startPos = new int[2]; + + if (w == 0 && h == 0) { + break; + } + + for (int i = 0; i < h; i++) { + char[] input = br.readLine().toCharArray(); + + for (int j = 0; j < w; j++) { + map[i][j] = input[j]; + + if (map[i][j] == 'o') { + startPos[0] = i; + startPos[1] = j; + } + + if (map[i][j] == '*') { + dirty++; + dirtyPos.add(new int[]{i, j}); + } + } + } + + distance = new int[dirty + 1][dirty + 1]; + dirtyPos.add(0, startPos); + + for (int i = 0; i <= dirty; i++) { + int[] start = dirtyPos.get(i); + + for (int j = i + 1; j <= dirty; j++) { + int[] end = dirtyPos.get(j); + + distance[i][j] = distance[j][i] = getDistance(start, end); + } + } + + order = new int[dirty + 1]; + used = new boolean[dirty + 1]; + + perm(1); + sb.append(answer + "\n"); + } + + System.out.println(sb); + } + + static void perm(int cnt) { + if (cnt == dirty + 1) { + // do + int dist = 0; + + for (int i = 0; i < order.length - 1; i++) { + int start = order[i]; + int end = order[i + 1]; + int d = distance[start][end]; + + if (d == -1) { + answer = -1; + return; + } + + dist += d; + } + + answer = Integer.min(answer, dist); + + return; + } + + for (int i = 1; i <= dirty; i++) { + if (used[i]) { + continue; + } + + used[i] = true; + order[cnt] = i; + perm(cnt + 1); + used[i] = false; + } + } + + static int getDistance(int[] start, int[] end) { + + Queue q = new ArrayDeque<>(); + boolean[][] visited = new boolean[h][w]; + q.offer(start); + visited[start[0]][start[1]] = true; + int dist = 0; + + while (!q.isEmpty()) { + int size = q.size(); + + while (size-- > 0) { + int[] pos = q.poll(); + int r = pos[0]; + int c = pos[1]; + + if (r == end[0] && c == end[1]) { + return dist; + } + + for (int d = 0; d < 4; d++) { + int nr = r + dr[d]; + int nc = c + dc[d]; + + if (nr < 0 || nc < 0 || nr == h || nc == w || visited[nr][nc] + || map[nr][nc] == 'x') { + continue; + } + + visited[nr][nc] = true; + q.offer(new int[]{nr, nc}); + } + } + + dist++; + } + + return -1; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week30/PG_81302.java" "b/src/\352\263\265\354\234\244\355\231\230/week30/PG_81302.java" new file mode 100644 index 0000000..6d133a4 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week30/PG_81302.java" @@ -0,0 +1,65 @@ +package d220407; + +public class PG_81302 { + + char[][] room; + boolean[][] visited; + int[] dr = {-1, 1, 0, 0}; + int[] dc = {0, 0, -1, 1}; + + public int[] solution(String[][] places) { + int[] answer = new int[places.length]; + room = new char[places.length][]; + + LOOP: + for (int p = 0; p < answer.length; p++) { + String[] place = places[p]; + + for (int i = 0; i < place.length; i++) { + room[i] = place[i].toCharArray(); + } + + for (int i = 0; i < 5; i++) { + for (int j = 0; j < 5; j++) { + if (room[i][j] != 'P') { + continue; + } + + visited = new boolean[5][5]; + + if (!dfs(i, j, 0)) { + answer[p] = 0; + continue LOOP; + } + } + } + + answer[p] = 1; + } + + return answer; + } + + boolean dfs(int i, int j, int cnt) { + if (cnt == 2) { + return true; + } + + visited[i][j] = true; + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == 5 || nc == 5 || room[nr][nc] == 'X' || visited[nr][nc]) { + continue; + } + + if (room[nr][nc] == 'P' || !dfs(nr, nc, cnt + 1)) { + return false; + } + } + + return true; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week32/BJ_16236.java" "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_16236.java" new file mode 100644 index 0000000..47498ff --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_16236.java" @@ -0,0 +1,115 @@ +package d220424; + +import java.util.*; +import java.io.*; + +/* +백준16236 아기 상어 + +풀이법 : + 1. bfs로 조건에 맞는 물고기 좌표를 찾습니다. + 2. 해당 물고기 까지 거리만큼 time을 더해줍니다. + 3. 조건에 맞는 물고기 좌표가 더이상 없다면 종료합니다. + +시간: 27m + */ + +public class BJ_16236 { + + static int n, m, shark, eat, r, c, time, map[][]; + static int[] dr = { -1, 1, 0, 0 }; + static int[] dc = { 0, 0, -1, 1 }; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + shark = 2; + eat = 0; + time = 0; + map = new int[n][n]; + + for (int i = 0; i < n; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + if (map[i][j] == 9) { + map[i][j] = 0; + r = i; + c = j; + } + } + } + + while (true) { + int[] fish = bfs(); // 시간, i, j + + if (fish == null) { + break; + } + + time += fish[0]; + r = fish[1]; // 상어 이동 + c = fish[2]; + + if (++eat == shark) { + shark++; + eat = 0; + } + } + + System.out.println(time); + } + + static int[] bfs() { + + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { + if (o1[0] != o2[0]) { + return Integer.compare(o1[0], o2[0]); + } + + if (o1[1] != o2[1]) { + return Integer.compare(o1[1], o2[1]); + } + + return Integer.compare(o1[2], o2[2]); + }); + boolean[][] visited = new boolean[n][n]; + pq.offer(new int[] { 0, r, c }); + + while (!pq.isEmpty()) { + int size = pq.size(); + + while (size-- > 0) { + int[] cur = pq.poll(); + int dist = cur[0]; + int i = cur[1]; + int j = cur[2]; + + if (map[i][j] > 0 && shark > map[i][j]) { + map[i][j] = 0; + return new int[] { dist, i, j }; + } + + if (visited[i][j]) { + continue; + } + + visited[i][j] = true; + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n || visited[nr][nc] || shark < map[nr][nc]) { + continue; + } + + pq.offer(new int[] { dist + 1, nr, nc }); + } + } + } + + return null; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week32/BJ_17142.java" "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_17142.java" new file mode 100644 index 0000000..e211fbd --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_17142.java" @@ -0,0 +1,139 @@ +package d220421; + +import java.io.*; +import java.util.*; + +/* +백준17142 연구소3 + +풀이법 : + 1. 바이러스 m개를 뽑아 bfs + 2. 이때 남은 빈칸이 없다면 bfs를 종료해줍니다. + +시간: 55m + */ + + +public class BJ_17142 { + + static int[] dr = { -1, 1, 0, 0 }; + static int[] dc = { 0, 0, -1, 1 }; + static int[][] map; + static List virusPos; + static int n, m, posLen, answer; + static boolean used[]; + + public static void main(String[] args) throws Exception { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + map = new int[n][n]; + virusPos = new ArrayList<>(); + answer = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + if (map[i][j] == 2) { + virusPos.add(new int[] { i, j }); + } + } + } + + posLen = virusPos.size(); + used = new boolean[posLen]; + + dfs(0, 0); + System.out.println(answer != Integer.MAX_VALUE ? answer : -1); + } + + // 바이러스 m개 뽑고 answer 갱신 + static void dfs(int cnt, int start) { + if (cnt == m) { + + Queue q = new ArrayDeque<>(); + int[][] tmp = new int[n][]; + boolean[][] visited = new boolean[n][n]; + int time = -1; + int empty = 0; + + // 시작 바이러스 초기화 및 빈칸 카운트 + for (int i = 0; i < n; i++) { + tmp[i] = map[i].clone(); + + for (int j = 0; j < n; j++) { + if (map[i][j] == 3) { + q.offer(new int[] { i, j }); + } + if (map[i][j] == 0) { + empty++; + } + } + } + + while (!q.isEmpty()) { + int size = q.size(); + + while (size-- > 0) { + int[] cur = q.poll(); + int r = cur[0]; + int c = cur[1]; + + if (visited[r][c]) { + continue; + } + + visited[r][c] = true; + + if (tmp[r][c] == 0) { + empty--; + } + + tmp[r][c] = 3; + + for (int d = 0; d < 4; d++) { + int nr = r + dr[d]; + int nc = c + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n || tmp[nr][nc] == 1 || visited[nr][nc]) { + continue; + } + + q.offer(new int[] { nr, nc }); + } + } + + time++; + + // 모든 칸 전파 완료 + if(empty==0) { + break; + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (tmp[i][j] == 0) { + return; + } + } + } + + answer = Integer.min(answer, time); + + return; + } + + for (int i = start; i < posLen; i++) { + + int[] virus = virusPos.get(i); + map[virus[0]][virus[1]] = 3; + dfs(cnt + 1, i + 1); + map[virus[0]][virus[1]] = 2; + + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week32/BJ_19238.java" "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_19238.java" new file mode 100644 index 0000000..44725fa --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_19238.java" @@ -0,0 +1,197 @@ +package d220423; + +import java.util.*; +import java.io.*; + +/* +백준19238 스타트 택시 + +풀이법 : + 1. 벽은 -1, 사람은 번호를 매겨 map을 생성합니다. + 2. 각 사람별로 도착지 좌표와 도착지 까지의 거리를 계산에 저장해둡니다. + 3. 사람들 중 한 명이라도 거리가 -1(도착지까지 막힘)이면 -1을 출력합니다. + 4. + +시간: 2h + */ + +public class BJ_19238 { + + static class Person { + int num; + int r; + int c; + int distance; + + public Person(int num, int r, int c, int distance) { + super(); + this.num = num; + this.r = r; + this.c = c; + this.distance = distance; + } + } + + static int n, m, taxiR, taxiC, fuel, map[][], personInfo[][]; + static int[] dr = { -1, 1, 0, 0 }; + static int[] dc = { 0, 0, -1, 1 }; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + fuel = Integer.parseInt(st.nextToken()); + map = new int[n][n]; + personInfo = new int[m + 1][]; // 도착지까지 거리 + 도착지 좌표 + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) { + map[i][j] = Integer.parseInt(st.nextToken()) == 0 ? 0 : -1; + } + } + + st = new StringTokenizer(br.readLine()); + taxiR = Integer.parseInt(st.nextToken()) - 1; + taxiC = Integer.parseInt(st.nextToken()) - 1; + + for (int i = 1; i <= m; i++) { + st = new StringTokenizer(br.readLine()); + int r = Integer.parseInt(st.nextToken()) - 1; + int c = Integer.parseInt(st.nextToken()) - 1; + int destR = Integer.parseInt(st.nextToken()) - 1; + int destC = Integer.parseInt(st.nextToken()) - 1; + int distance = getDistance(r, c, destR, destC); + + // 도착지까지 막혀있음 + if (distance < 0) { + System.out.println(-1); + return; + } + + map[r][c] = i; + personInfo[i] = new int[] { distance, destR, destC }; + } + + // m명의 사람을 다 태울때까지 + while (m > 0) { + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { + if (o1[0] != o2[0]) { + return Integer.compare(o1[0], o2[0]); + } + + if (o1[1] != o2[1]) { + return Integer.compare(o1[1], o2[1]); + } + + return Integer.compare(o1[2], o2[2]); + }); + + pq.offer(new int[] { 0, taxiR, taxiC }); + boolean[][] visited = new boolean[n][n]; + int person = 0; // 제일 가까운 사람 번호 + int taxiToPerson = 0; // 그 사람까지 거리 + + // 제일 가까운 사람 찾기 + LOOP: while (!pq.isEmpty()) { + int size = pq.size(); + + while (size-- > 0) { + int[] cur = pq.poll(); + int r = cur[1]; + int c = cur[2]; + person = map[r][c]; + + if (visited[r][c]) { + continue; + } + + visited[r][c] = true; + + // 사람 찾으면 그 칸 0으로 바꾸고 종료 + if (person > 0) { + map[r][c] = 0; + break LOOP; + } + + for (int d = 0; d < 4; d++) { + int nr = r + dr[d]; + int nc = c + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n || map[nr][nc] == -1) { + continue; + } + + pq.offer(new int[] { taxiToPerson + 1, nr, nc }); + } + } + + taxiToPerson++; + } + + // 태울 사람 못찾으면 -1 출력 + if (person <= 0) { + System.out.println(-1); + return; + } + + // 그 사람 목적지로 택시 이동 + int personToDest = personInfo[person][0]; + taxiR = personInfo[person][1]; + taxiC = personInfo[person][2]; + + // 연료 모자람 + if (fuel < taxiToPerson + personToDest) { + System.out.println(-1); + return; + } + + fuel = fuel - taxiToPerson + personToDest; + m--; + } + + System.out.println(m == 0 ? fuel : -1); + } + + // getDistance: 두 좌표 사이 최소거리 + static int getDistance(int r, int c, int destR, int destC) { + Queue q = new ArrayDeque(); + q.offer(new int[] { r, c }); + boolean[][] visited = new boolean[n][n]; + int dist = 0; + + while (!q.isEmpty()) { + int size = q.size(); + while (size-- > 0) { + int[] cur = q.poll(); + int i = cur[0]; + int j = cur[1]; + + if (visited[i][j]) { + continue; + } + + visited[i][j] = true; + + if (i == destR && j == destC) { + return dist; + } + + for (int d = 0; d < 4; d++) { + int nr = i + dr[d]; + int nc = j + dc[d]; + if (nr < 0 || nc < 0 || nr == n || nc == n || map[nr][nc] == -1) { + continue; + } + + q.offer(new int[] { nr, nc }); + } + } + + dist++; + } + + return -1; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week32/BJ_1938.java" "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_1938.java" new file mode 100644 index 0000000..f24ace2 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_1938.java" @@ -0,0 +1,129 @@ +package d220425; + +import java.util.*; +import java.io.*; + +/* +백준1938 통나무 옮기기 + +풀이법 : + 1. bfs로 세 좌표 모두 E가 되는 점을 찾습니다. + 2. 방문 관리는 3차원 배열로 관리하고 세 좌표가 모두 방문했을때만 방문한 것으로 간주합니다. + 3. 8방을 체크하여 모두 비어있다면 회전한 좌표도 큐에 추가합니다. + + */ + +public class BJ_1938 { + + static class Log { + int type; + int[] left; + int[] center; + int[] right; + + public Log(int type, int[] left, int[] center, int[] right) { + super(); + this.type = type; + this.left = left; + this.center = center; + this.right = right; + } + } + + static int[] dr = { -1, 1, 0, 0, -1, -1, 1, 1 }; + static int[] dc = { 0, 0, -1, 1, -1, 1, -1, 1 }; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int n = Integer.parseInt(br.readLine()); + char[][] map = new char[n][n]; + int[][] start = new int[3][]; + int idx = 0; + int startType; + + for (int i = 0; i < n; i++) { + char[] input = br.readLine().toCharArray(); + for (int j = 0; j < n; j++) { + map[i][j] = input[j]; + + if (map[i][j] == 'B') { + start[idx++] = new int[] { i, j }; + } + } + } + + startType = start[0][0] == start[1][0] ? 0 : 1; // 0: 가로, 1: 세로 + Queue q = new ArrayDeque<>(); + q.offer(new Log(startType, start[0], start[1], start[2])); + int dist = 0; + boolean[][][] visited = new boolean[2][n][n]; + + while (!q.isEmpty()) { + int size = q.size(); + + LOOP: while (size-- > 0) { + Log log = q.poll(); + int type = log.type; + int lr = log.left[0]; // 왼쪽or위 행좌표 + int lc = log.left[1]; // 왼쪽or위 열좌표 + int cr = log.center[0]; // 중앙 행좌표 + int cc = log.center[1]; // 중앙 행좌표 + int rr = log.right[0]; // 오른쪽or아래 행좌표 + int rc = log.right[1]; // 오른쪽or아래 행좌표 + + // 세 점 모두 도착 + if (map[lr][lc] == 'E' && map[cr][cc] == 'E' && map[rr][rc] == 'E') { + System.out.println(dist); + return; + } + + // 세 점 모두 동시에 방문한 적 있음 + if (visited[type][lr][lc] && visited[type][cr][cc] && visited[type][rr][rc]) { + continue; + } + + visited[type][lr][lc] = visited[type][cr][cc] = visited[type][rr][rc] = true; + + for (int d = 0; d < 4; d++) { + int nlr = lr + dr[d]; + int nlc = lc + dc[d]; + int ncr = cr + dr[d]; + int ncc = cc + dc[d]; + int nrr = rr + dr[d]; + int nrc = rc + dc[d]; + + if (nlr < 0 || nlc < 0 || ncr < 0 || ncc < 0 || nrr < 0 || nrc < 0 || nlr == n || nlc == n + || ncr == n || ncc == n || nrr == n || nrc == n || map[nlr][nlc] == '1' + || map[ncr][ncc] == '1' || map[nrr][nrc] == '1') { + continue; + } + + q.offer(new Log(type, new int[] { nlr, nlc }, new int[] { ncr, ncc }, new int[] { nrr, nrc })); + } + + // 회전 가능 여부 체크 + for (int d = 0; d < 8; d++) { + int nr = cr + dr[d]; + int nc = cc + dc[d]; + + if (nr < 0 || nc < 0 || nr == n || nc == n || map[nr][nc] == '1') { + continue LOOP; + } + } + + // 회전한 점 큐에 추가 + int nlr = type == 0 ? lr + dr[5] : lr + dr[6]; + int nlc = type == 0 ? lc + dc[5] : lc + dc[6]; + int nrr = type == 0 ? rr + dr[6] : rr + dr[5]; + int nrc = type == 0 ? rc + dc[6] : rc + dc[5]; + + q.offer(new Log(type ^ 1, new int[] { nlr, nlc }, new int[] { cr, cc }, new int[] { nrr, nrc })); + } + + dist++; + } + + System.out.println(0); + } + +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week32/BJ_20061.java" "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_20061.java" new file mode 100644 index 0000000..bb01ca3 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week32/BJ_20061.java" @@ -0,0 +1,186 @@ +package d220421; + +import java.util.*; +import java.io.*; + +/* +백준20061 모노미노도미노 2 + +풀이법 : + 1. 파랑, 초록 영역 모두 6x4로 관리합니다. + 2. 행 내리는 작업은 그냥 참조값 바꿔주는 식으로 작성했습니다. + +시간: 2h 10m + */ + +public class BJ_20061 { + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = null; + + int score = 0; + boolean[][] blue = new boolean[6][4]; + boolean[][] green = new boolean[6][4]; + + int n = Integer.parseInt(br.readLine()); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + int type = Integer.parseInt(st.nextToken()); + int x = Integer.parseInt(st.nextToken()); + int y = Integer.parseInt(st.nextToken()); + int blueCol = type != 3 ? 4 - x - 1 : 4 - x - 2; + int blueType = type; + + if (type != 1) { + blueType = type == 3 ? 2 : 3; + } + + down(green, y, type); + down(blue, blueCol, blueType); + + score += removeRow(green) + removeRow(blue); + + checkSpecial(green); + checkSpecial(blue); + } + + System.out.println(score); + System.out.println(getCnt(green) + getCnt(blue)); + } + + // 초록, 파랑 영역에 블록 위치시키기 + static void down(boolean[][] board, int col, int type) { + switch (type) { + + case 1: + for (int i = 0; i < 6; i++) { + board[i][col] = true; + + if (i == 5) { + break; + } + + if (i < 5 && board[i + 1][col]) { + break; + } + + board[i][col] = false; + } + break; + + case 2: + for (int i = 0; i < 6; i++) { + board[i][col] = board[i][col + 1] = true; + + if (i == 5) { + break; + } + + if (i < 5 && (board[i + 1][col] || board[i + 1][col + 1])) { + break; + } + + board[i][col] = board[i][col + 1] = false; + } + break; + + case 3: + for (int i = 0; i < 5; i++) { + board[i][col] = true; + board[i + 1][col] = true; + + if (i == 4) { + break; + } + + if (i < 4 && board[i + 2][col]) { + break; + } + + board[i][col] = board[i + 1][col] = false; + } + break; + } + + } + + // 이어진 행 있으면 카운트 및 배열 행 조정 + static int removeRow(boolean[][] board) { + + int cnt = 0; + int start = -1; + + LOOP: for (int i = 5; i >= 0; i--) { + + for (int j = 0; j < 4; j++) { + if (!board[i][j]) { + continue LOOP; + } + } + + if (cnt == 0) { + start = i; + } + cnt++; + } + + if (cnt == 0) { + return 0; + } + + // 삭제한 행 개수만큼 참조값 조작 + for (int k = start; k >= 2; k--) { + board[k] = board[k - cnt]; + } + + for (int k = 0; k < cnt; k++) { + board[1 - k] = new boolean[4]; + } + + return cnt; + } + + // 0행, 1행 영역 확인 + static void checkSpecial(boolean[][] board) { + int cnt = 0; + + LOOP: for (int i = 1; i >= 0; i--) { + + for (int j = 0; j < 4; j++) { + if (board[i][j]) { + cnt++; + continue LOOP; + } + } + } + + if (cnt == 0) { + return; + } + + for (int k = 5; k >= 2; k--) { + board[k] = board[k - cnt]; + } + + for (int k = 0; k < 2; k++) { + board[k] = new boolean[4]; + } + + return; + } + + static int getCnt(boolean[][] board) { + int cnt = 0; + + for (int i = 0; i < 6; i++) { + for (int j = 0; j < 4; j++) { + if (board[i][j]) + cnt++; + } + } + + return cnt; + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14499.java" "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14499.java" new file mode 100644 index 0000000..7de0a3c --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14499.java" @@ -0,0 +1,115 @@ +package d220429; + +import java.util.*; + +import java.io.*; + +/* +백준14499 주사위 굴리기 + +풀이법 : + 1. 주사위 클래스를 생성하고 roll 메소드를 생성합니다. + 2. 주어진대로 굴리고 방향대로 roll + +시간: 28m + */ + +public class BJ_14499 { + + static int n, m, x, y, k, map[][]; + static int[] dr = { 0, 0, 0, -1, 1 }; + static int[] dc = { 0, 1, -1, 0, 0 }; + + static class Dice { + int top; + int bottom; + int left; + int right; + int front; + int back; + + void roll(int d) { + int tmp = 0; + + switch (d) { + + case 1: + tmp = right; + right = top; + top = left; + left = bottom; + bottom = tmp; + break; + case 2: + tmp = left; + left = top; + top = right; + right = bottom; + bottom = tmp; + break; + case 3: + tmp = back; + back = top; + top = front; + front = bottom; + bottom = tmp; + break; + case 4: + tmp = front; + front = top; + top = back; + back = bottom; + bottom = tmp; + break; + } + } + } + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + StringBuilder sb = new StringBuilder(); + + n = Integer.parseInt(st.nextToken()); + m = Integer.parseInt(st.nextToken()); + x = Integer.parseInt(st.nextToken()); + y = Integer.parseInt(st.nextToken()); + k = Integer.parseInt(st.nextToken()); + map = new int[n][m]; + Dice dice = new Dice(); + + for (int i = 0; i < n; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < m; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < k; i++) { + int d = Integer.parseInt(st.nextToken()); + + int nx = x + dr[d]; + int ny = y + dc[d]; + + if (nx < 0 || ny < 0 || nx == n || ny == m) { + continue; + } + + dice.roll(d); + + if (map[nx][ny] == 0) { + map[nx][ny] = dice.bottom; + } else { + dice.bottom = map[nx][ny]; + map[nx][ny] = 0; + } + + x = nx; + y = ny; + sb.append(dice.top+"\n"); + } + + System.out.println(sb); + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14888.java" "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14888.java" new file mode 100644 index 0000000..d05c6c9 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_14888.java" @@ -0,0 +1,79 @@ +package d220429; + +import java.io.*; +import java.util.*; + +/* +백준14888 연산자 끼워넣기 + +풀이법 : + 1. 완전탐색 + +시간: 17m + */ + +public class BJ_14888 { + + static int n, min, max, num[], op[]; + static boolean used[]; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + n = Integer.parseInt(br.readLine()); + StringTokenizer st = new StringTokenizer(br.readLine()); + num = new int[n]; + op = new int[4]; + used = new boolean[4]; + min = Integer.MAX_VALUE; + max = Integer.MIN_VALUE; + + for (int i = 0; i < n; i++) { + num[i] = Integer.parseInt(st.nextToken()); + } + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < 4; i++) { + op[i] = Integer.parseInt(st.nextToken()); + } + + dfs(0, num[0]); + System.out.println(max); + System.out.println(min); + + } + + static void dfs(int cnt, int score) { + if (cnt == n-1) { + min = Integer.min(score, min); + max = Integer.max(score, max); + return; + } + + for (int i = 0; i < 4; i++) { + if (op[i] == 0) { + continue; + } + + op[i]--; + dfs(cnt + 1, operate(score, num[cnt + 1], i)); + op[i]++; + } + } + + static int operate(int a, int b, int type) { + + switch (type) { + case 0: + return a + b; + case 1: + return a - b; + case 2: + return a * b; + case 3: + return a / b; + } + + return -1; + + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week33/BJ_17140.java" "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_17140.java" new file mode 100644 index 0000000..75ecb8c --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_17140.java" @@ -0,0 +1,196 @@ +package d220429; + +import java.io.*; +import java.util.*; + +/* +백준17140 이차원 배열과 연산 + +풀이법 : + 1. 이차원 List로 배열 관리 + 2. 각 행, 열별로 정렬 + 3. 배열이 작아져 r,c 조회 못하는 경우 Index 에러 주의 + +시간: 1h + */ + +public class BJ_17140 { + + static int r, c, k, time; + static List> map; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + r = Integer.parseInt(st.nextToken()) - 1; + c = Integer.parseInt(st.nextToken()) - 1; + k = Integer.parseInt(st.nextToken()); + time = 0; + map = new ArrayList<>(); + + for (int i = 0; i < 3; i++) { + List list = new ArrayList<>(); + st = new StringTokenizer(br.readLine()); + + for (int j = 0; j < 3; j++) { + list.add(Integer.parseInt(st.nextToken())); + } + + map.add(list); + } + + while (time <= 100) { + if (r < map.size() && c < map.get(0).size() && map.get(r).get(c) == k) { + System.out.println(time); + return; + } + + time++; + + if (map.size() >= map.get(0).size()) { + sortRow(); + } else { + sortCol(); + } + } + + System.out.println(-1); + } + + // 열 별로 정렬 + private static void sortCol() { + int max = map.size(); + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { + if (o1[1] != o2[1]) { + return Integer.compare(o1[1], o2[1]); + } + return Integer.compare(o1[0], o2[0]); + }); + List> newList = new ArrayList<>(); + + // 기존 열 길이만큼 ArrayList 생성 + for (int i = 0; i < max; i++) { + newList.add(new ArrayList<>()); + } + + // 열 별로 정렬 + for (int j = 0; j < map.get(0).size(); j++) { + Map count = new HashMap<>(); + for (int i = 0; i < map.size(); i++) { + int num = map.get(i).get(j); + + if (map.get(i).get(j) == 0) { + continue; + } + + if (count.get(num) == null) { + count.put(num, 0); + } + + count.put(num, count.get(num) + 1); + } + + for (int num : count.keySet()) { + pq.offer(new int[] { num, count.get(num) }); + } + + List tmp = new ArrayList<>(); + + while (!pq.isEmpty()) { + int[] cur = pq.poll(); + tmp.add(cur[0]); + tmp.add(cur[1]); + } + + // 생성된 list보다 열이 더 많으면 더 추가 + if (tmp.size() > max) { + + for (int x = 0; x < tmp.size() - max; x++) { + List list = new ArrayList<>(); + + for (int y = 0; y < j; y++) { + list.add(0); + } + + newList.add(list); + } + + max = tmp.size(); + } + + for (int x = 0; x < max; x++) { + if (x > tmp.size() - 1) { + newList.get(x).add(0); + } else { + newList.get(x).add(tmp.get(x)); + } + } + } + + if (newList.size() > 100) { + newList = newList.subList(0, 100); + } + + map = newList; + } + + // 행 별로 정렬 + private static void sortRow() { + int max = 0; + + for (int i = 0; i < map.size(); i++) { + + List row = map.get(i); + Map count = new HashMap<>(); + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> { + if (o1[1] != o2[1]) { + return Integer.compare(o1[1], o2[1]); + } + return Integer.compare(o1[0], o2[0]); + }); + + for (int j = 0; j < row.size(); j++) { + if (row.get(j) == 0) { + continue; + } + + if (count.get(row.get(j)) == null) { + count.put(row.get(j), 0); + } + + count.put(row.get(j), count.get(row.get(j)) + 1); + } + + // 숫자 카운트한거 pq로 정렬 + for (int num : count.keySet()) { + pq.offer(new int[] { num, count.get(num) }); + } + + List tmp = new ArrayList<>(); + + while (!pq.isEmpty()) { + int[] cur = pq.poll(); + tmp.add(cur[0]); + tmp.add(cur[1]); + } + + // 정렬한 list로 대체 및 행 최대길이 갱신 + map.set(i, tmp); + max = Integer.max(max, tmp.size()); + } + + // 모자란 부분 0 채우기 혹은 100넘어가면 자르기 + for (int i = 0; i < map.size(); i++) { + List row = map.get(i); + int cnt = max - row.size(); + + for (int j = 0; j < cnt; j++) { + row.add(0); + } + + if (row.size() > 100) { + row = row.subList(0, 100); + } + } + } +} diff --git "a/src/\352\263\265\354\234\244\355\231\230/week33/BJ_23289.java" "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_23289.java" new file mode 100644 index 0000000..8195312 --- /dev/null +++ "b/src/\352\263\265\354\234\244\355\231\230/week33/BJ_23289.java" @@ -0,0 +1,219 @@ +package d220427; + +import java.util.*; +import java.io.*; + +public class BJ_23289 { + + static int r, c, k, w, answer, map[][]; + static boolean[][][] wall; + static List checkPos, heater; + static List spreadMap; + static int[][] dr = { {}, { 0, -1, 1 }, { 0, -1, 1 }, { -1, -1, -1 }, { 1, 1, 1 } }; + static int[][] dc = { {}, { 1, 1, 1 }, { -1, -1, -1 }, { 0, -1, 1 }, { 0, -1, 1 } }; + + public static void main(String[] args) throws Exception { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + r = Integer.parseInt(st.nextToken()); + c = Integer.parseInt(st.nextToken()); + k = Integer.parseInt(st.nextToken()); + map = new int[r][c]; + wall = new boolean[2][][]; + wall[0] = new boolean[r - 1][c]; // 가로벽 + wall[1] = new boolean[r][c - 1]; // 세로벽 + checkPos = new ArrayList<>(); + heater = new ArrayList<>(); + spreadMap = new ArrayList<>(); + answer = 0; + + for (int i = 0; i < r; i++) { + st = new StringTokenizer(br.readLine()); + + for (int j = 0; j < c; j++) { + int val = Integer.parseInt(st.nextToken()); + + if (val == 0) { + continue; + } + + if (val == 5) { + checkPos.add(new int[] { i, j }); + continue; + } + + heater.add(new int[] { i, j, val }); + } + } + + w = Integer.parseInt(br.readLine()); + + for (int i = 0; i < w; i++) { + st = new StringTokenizer(br.readLine()); + + int x = Integer.parseInt(st.nextToken()) - 1; + int y = Integer.parseInt(st.nextToken()) - 1; + int t = Integer.parseInt(st.nextToken()); + + x = t == 0 ? x - 1 : x; + + wall[t][x][y] = true; + } + + for (int[] h : heater) { + spreadMap.add(makeSpread(h)); + } + + + while (true) { + wind(); + + adjust(); + + decrease(); + + if (++answer > 100) { + System.out.println(101); + return; + } + + if (check()) + break; + } + + System.out.println(answer); + } + + static int[][] makeSpread(int[] heater) { + int[][] spread = new int[r][c]; + boolean[][] visited = new boolean[r][c]; + + dfs(heater[0] + dr[heater[2]][0], heater[1] + dc[heater[2]][0], heater[2], 5, spread, visited); + + return spread; + } + + static void dfs(int i, int j, int dir, int cnt, int[][] spread, boolean[][] visited) { + + if (visited[i][j] || cnt == 0) { + return; + } + + spread[i][j] = cnt; + visited[i][j] = true; + int wallIdx = dir <= 2 ? 1 : 0; + int wallR = dir == 3 ? i - 1 : i; + int wallC = dir == 2 ? j - 1 : j; + + for (int d = 0; d < 3; d++) { + int nr = i + dr[dir][d]; + int nc = j + dc[dir][d]; + + if (nr < 0 || nc < 0 || nr == r || nc == c) { + continue; + } + + if (d == 0 && !wall[wallIdx][wallR][wallC]) { + dfs(nr, nc, dir, cnt - 1, spread, visited); + } + + if (d > 0) { + // 오 왼 + if (dir <= 2) { + int tR = d == 1 ? wallR - 1 : wallR; + int tC = wallC; + + if (!wall[wallIdx ^ 1][tR][tC] && !wall[wallIdx][wallR + dr[dir][d]][wallC]) { + dfs(nr, nc, dir, cnt - 1, spread, visited); + } + } + + // 위 아래 + else { + int tR = wallR; + int tC = d == 1 ? wallC - 1 : wallC; + + if (!wall[wallIdx ^ 1][tR][tC] && !wall[wallIdx][wallR][wallC + dc[dir][d]]) { + dfs(nr, nc, dir, cnt - 1, spread, visited); + } + } + } + + } + } + + static void wind() { + for (int[][] s : spreadMap) { + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + map[i][j] += s[i][j]; + } + } + } + } + + static void adjust() { + int[][] tmp = new int[r][c]; + boolean[][] visited = new boolean[r][c]; + + for (int i = 0; i < r; i++) { + int j = i % 2 == 0 ? 0 : 1; + for (; j < c; j += 2) { + + visited[i][j] = true; + + for (int d = 1; d <= 4; d++) { + int nr = i + dr[d][0]; + int nc = j + dc[d][0]; + + if (nr < 0 || nc < 0 || nr == r || nc == c) { + continue; + } + + int wallIdx = d <= 2 ? 1 : 0; + int wallR = d == 3 ? i - 1 : i; + int wallC = d == 2 ? j - 1 : j; + + if (wall[wallIdx][wallR][wallC]) { + continue; + } + + int dif = (map[i][j] - map[nr][nc]) / 4; + + tmp[i][j] -= dif; + tmp[nr][nc] += dif; + } + } + } + + for (int i = 0; i < r; i++) { + for (int j = 0; j < c; j++) { + map[i][j] += tmp[i][j]; + } + } + } + + static void decrease() { + for (int i = 0; i < r; i++) { + map[i][0] = Integer.max(0, map[i][0] - 1); + map[i][c - 1] = Integer.max(0, map[i][c - 1] - 1); + } + + for (int j = 1; j < c - 1; j++) { + map[0][j] = Integer.max(0, map[0][j] - 1); + map[r - 1][j] = Integer.max(0, map[r - 1][j]-1); + } + } + + static boolean check() { + for (int pos[] : checkPos) { + if (map[pos[0]][pos[1]] < k) { + return false; + } + } + + return true; + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ10282.java" "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ10282.java" new file mode 100644 index 0000000..35c0b47 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ10282.java" @@ -0,0 +1,73 @@ +package BJ; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +/* + * 10282. 해킹 + * ["컴퓨터 a가 다른 컴퓨터 b에 의존","총 감염된 컴퓨터","걸리는 시간"] => 그래프 알고리즘(방문 가능 여부,cost) + * MST? Dijkstra? => cost의 합계 X => Dijkstra +*/ + +public class BJ10282 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int T = Integer.parseInt(br.readLine()); + int N, D, C, A, B, S; + for (int tc = 0; tc < T; tc++) { + st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + D = Integer.parseInt(st.nextToken()); + C = Integer.parseInt(st.nextToken()); + + ArrayList[] nodeList = new ArrayList[N+1]; + for (int i = 0; i < N + 1; i++) nodeList[i] = new ArrayList(); + for (int i = 0; i < D; i++) { + st = new StringTokenizer(br.readLine()); + A = Integer.parseInt(st.nextToken()); + B = Integer.parseInt(st.nextToken()); + S = Integer.parseInt(st.nextToken()); + nodeList[B].add(new int[] {A, S}); + } + + PriorityQueue pq = new PriorityQueue((o1, o2) -> o1[1] - o2[1]); + pq.add(new int[] {C, 0}); + int[] cost = new int[N+1]; + Arrays.fill(cost, Integer.MAX_VALUE); + cost[C] = 0; + int[] cur; + int temp; + + while (!pq.isEmpty()) { + cur = pq.poll(); + if (cost[cur[0]] < cur[1]) continue; + for (int[] node : nodeList[cur[0]]) { + temp = cur[1] + node[1]; + if (temp < cost[node[0]]) { + cost[node[0]] = temp; + pq.add(new int[] {node[0], temp}); + } + } + } + + int resNum = 0, resCost = 0; + for (int c : cost) { + if (c != Integer.MAX_VALUE) { + resNum++; + if (c > resCost) resCost = c; + } + } + + System.out.println(resNum + " " + resCost); + + } + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ2467.java" "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ2467.java" new file mode 100644 index 0000000..ab8ccc8 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/BJ2467.java" @@ -0,0 +1,47 @@ +package BJ; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/* + * 2467. 용액 +*/ + +public class BJ2467 { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int n = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + int[] arr = new int[n]; + for (int i = 0; i < n; i++) + arr[i] = Integer.parseInt(st.nextToken()); + int lef = 0, rig = n - 1; + int lefVal = arr[lef], rigVal = arr[rig]; + int optVal = Integer.MAX_VALUE, temp; + + while (true) { + temp = arr[lef] + arr[rig]; + if (Math.abs(temp) <= optVal) { + optVal = Math.abs(temp); + lefVal = arr[lef]; + rigVal = arr[rig]; + } + if (lef + 1 >= rig) break; + if (temp < 0) { + if (arr[rig] > 0) lef++; + else lef = rig - 1; + }else if (temp > 0) { + if (arr[lef] < 0) rig--; + else rig = lef + 1; + }else break; + } + + System.out.println(lefVal + " " + rigVal); + + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG1832.java" "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG1832.java" new file mode 100644 index 0000000..07af873 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG1832.java" @@ -0,0 +1,63 @@ +package PG; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/* + * Level3. 보행자 천국 + * ["오른쪽 또는 아래 방향으로 한 칸씩 이동","20170805로 나눈 나머지",1 <= m,n <= 500] ==> DP +*/ + +public class PG1832 { + final static int MOD = 20170805; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int m = Integer.parseInt(st.nextToken()); + int n = Integer.parseInt(st.nextToken()); + int[][] cityMap = new int[m][n]; + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < n; j++) + cityMap[i][j] = Integer.parseInt(st.nextToken()); + } + + int[][][] DP = new int[2][m][n]; + for (int i = 0; i < m; i++) { + if (cityMap[i][0] == 1) break; + DP[0][i][0] = 1; + } + for (int j = 0; j < n; j++) { + if (cityMap[0][j] == 1) break; + DP[1][0][j] = 1; + } + + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + if (cityMap[i][j] == 1) continue; + if (cityMap[i-1][j] == 0) DP[0][i][j] = (DP[0][i-1][j] + DP[1][i-1][j]) % MOD; + else DP[0][i][j] = DP[0][i-1][j]; + if (cityMap[i][j-1] == 0) DP[1][i][j] = (DP[1][i][j-1] + DP[0][i][j-1]) % MOD; + else DP[1][i][j] = DP[1][i][j-1]; + } + } + +// for (int i = 0; i < m; i++) { +// for (int j = 0; j < n; j++) +// System.out.print(DP[0][i][j] + " "); +// System.out.println(); +// } +// System.out.println(); +// for (int i = 0; i < m; i++) { +// for (int j = 0; j < n; j++) +// System.out.print(DP[1][i][j] + " "); +// System.out.println(); +// } + + System.out.println((DP[0][m-1][n-1] + DP[1][m-1][n-1]) % MOD); + + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG81303.java" "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG81303.java" new file mode 100644 index 0000000..deae570 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week17(211227)/PG81303.java" @@ -0,0 +1,75 @@ +package PG; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Stack; +import java.util.StringTokenizer; + + +/* + * Level3. 표 편집 +*/ + +public class PG81303 { + + static class Node { + boolean state; + Node prev, next; + public Node() { + this.state = true; + this.prev = null; + this.next = null; + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int n = Integer.parseInt(st.nextToken()); + int k = Integer.parseInt(st.nextToken()); + Node[] nodeList = new Node[n]; + for (int i = 0; i < n; i++) nodeList[i] = new Node(); + for (int i = 1; i < n; i++) { + nodeList[i-1].next = nodeList[i]; + nodeList[i].prev = nodeList[i-1]; + } + st = new StringTokenizer(br.readLine(), ","); + String str; + int temp; + Node cur = nodeList[k], undo; + Stack stack = new Stack<>(); + while (st.hasMoreElements()) { + str = st.nextToken(); + if (str.charAt(0) == 'U') { + temp = Integer.parseInt(str.substring(2)); + for (int i = 0; i < temp; i++) cur = cur.prev; + } else if (str.charAt(0) == 'D') { + temp = Integer.parseInt(str.substring(2)); + for (int i = 0; i < temp; i++) cur = cur.next; + } else if (str.charAt(0) == 'C') { + cur.state = false; + stack.push(cur); + if (cur.prev != null) cur.prev.next = cur.next; + if (cur.next != null) { + cur.next.prev = cur.prev; + cur = cur.next; + } else cur = cur.prev; + } else { + undo = stack.pop(); + undo.state = true; + if (undo.prev != null) undo.prev.next = undo; + if (undo.next != null) undo.next.prev = undo; + } + } + + StringBuilder sb = new StringBuilder(); + for (Node node : nodeList) { + if (node.state) sb.append('O'); + else sb.append('X'); + } + System.out.println(sb.toString()); + + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1005.java" "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1005.java" new file mode 100644 index 0000000..77ae3ef --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1005.java" @@ -0,0 +1,59 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ1005 { + /* 1005. ACM Craft + 건설 순서 규칙 => 위상정렬 + */ + static int[] dist; + // 건물 w를 짓기 위해 필요한 건물들을 DFS + public static void dfs(ArrayList[] nodeList, int[] cost, int w) { + if (nodeList[w].size() == 0) { + dist[w] = cost[w]; + return; + } + int temp = Integer.MIN_VALUE; + for (int x:nodeList[w]) { + // dist[x] >= 0이면 이미 비용이 계산된 건물 + if (dist[x] < 0) dfs(nodeList, cost, x); + temp = Math.max(temp, dist[x]); + } + dist[w] = temp + cost[w]; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int T = Integer.parseInt(br.readLine()); + int N, K, X, Y, W; + int[] cost; + ArrayList[] nodeList; + for (int t = 0; t < T; t++) { + st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + K = Integer.parseInt(st.nextToken()); + cost = new int[N+1]; + st = new StringTokenizer(br.readLine()); + for (int i = 1; i < N + 1; i++) cost[i] = Integer.parseInt(st.nextToken()); + nodeList = new ArrayList[N+1]; + for (int i = 1; i < N + 1; i++) nodeList[i] = new ArrayList<>(); + for (int i = 0; i < K; i++) { + st = new StringTokenizer(br.readLine()); + X = Integer.parseInt(st.nextToken()); + Y = Integer.parseInt(st.nextToken()); + nodeList[Y].add(X); + } + W = Integer.parseInt(br.readLine()); + dist = new int[N+1]; + Arrays.fill(dist, Integer.MIN_VALUE); + dfs(nodeList, cost, W); + System.out.println(dist[W]); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1238.java" "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1238.java" new file mode 100644 index 0000000..92dda26 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ1238.java" @@ -0,0 +1,54 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ1238 { + /* 1238. 파티 + N개의 node에서 최단거리 => Floyd-Warshall 알고리즘 + */ + final static int MAX_N = 1000; + final static int MAX_T = 100; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int X = Integer.parseInt(st.nextToken()); + int[][] DP = new int[N+1][N+1]; + for (int i = 0; i < N + 1; i++) { + Arrays.fill(DP[i], MAX_N * MAX_T); + DP[i][i] = Integer.MIN_VALUE; + } + int A, B, T, result = Integer.MIN_VALUE; + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + A = Integer.parseInt(st.nextToken()); + B = Integer.parseInt(st.nextToken()); + T = Integer.parseInt(st.nextToken()); + DP[A][B] = T; + } + // Floyd-Warshall 알고리즘 + for (int k = 1; k < N+1; k++) { + for (int i = 1; i < N+1; i++) { + if (i == k) continue; + for (int j = 1; j < N+1; j++) { + if (i == j || j == k) continue; + DP[i][j] = Math.min(DP[i][j], DP[i][k] + DP[k][j]); + } + } + } +// for (int i = 1; i < N + 1; i++) { +// for (int j = 1; j < N + 1; j++) +// System.out.print(DP[i][j] + " "); +// System.out.println(); +// } + // 대칭원소 합의 최댓값 + for (int i = 1; i < N + 1; i++) result = Math.max(result, DP[i][X] + DP[X][i]); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ14499.java" "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ14499.java" new file mode 100644 index 0000000..29a45dc --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ14499.java" @@ -0,0 +1,79 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ14499 { + /* 14499. 주사위 굴리기 + 시뮬레이션 + */ + final static int[] dx = {0, 0, -1, 1}; + final static int[] dy = {1, -1, 0, 0}; + public static void rollDice(int[] dice, int d) { + int temp = dice[0]; + switch (d) { + case 1: + dice[0] = dice[2]; + dice[2] = dice[5]; + dice[5] = dice[3]; + dice[3] = temp; + break; + case 2: + dice[0] = dice[3]; + dice[3] = dice[5]; + dice[5] = dice[2]; + dice[2] = temp; + break; + case 3: + dice[0] = dice[4]; + dice[4] = dice[5]; + dice[5] = dice[1]; + dice[1] = temp; + break; + case 4: + dice[0] = dice[1]; + dice[1] = dice[5]; + dice[5] = dice[4]; + dice[4] = temp; + break; + default: + break; + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int x = Integer.parseInt(st.nextToken()); + int y = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + int[][] map = new int[N][M]; + int[] cmd = new int[K]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < M; j++) + map[i][j] = Integer.parseInt(st.nextToken()); + } + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < K; i++) cmd[i] = Integer.parseInt(st.nextToken()); + int[] dice = new int[6]; + + for (int c:cmd) { + if (x + dx[c-1] < 0 || x + dx[c-1] >= N || y + dy[c-1] < 0 || y + dy[c-1] >= M) continue; + x += dx[c-1]; + y += dy[c-1]; + rollDice(dice, c); + if (map[x][y] == 0) { + map[x][y] = dice[5]; + }else { + dice[5] = map[x][y]; + map[x][y] = 0; + } + System.out.println(dice[0]); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ16637.java" "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ16637.java" new file mode 100644 index 0000000..a223a37 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week18(220103)/BJ16637.java" @@ -0,0 +1,57 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ16637 { + /* 16637. 괄호 추가하기 + [1 <= N <= 19] => 최대 연산자 9개 => 2^9 => DFS + */ + static int M; + static int[] nums; + static char[] ops; + static int result = Integer.MIN_VALUE; + + public static void dfs(int idx, int res) { + if (idx >= M) { + if (res > result) result = res; + return; + } + // 괄호 없이 + int t = res; + if (ops[idx] == '+') t += nums[idx]; + else if (ops[idx] == '-') t -= nums[idx]; + else t *= nums[idx]; + dfs(idx + 1, t); + // 다음 연산자에 괄호 추가 + if (idx < M - 1) { + t = res; + int s; + // 괄호 내부 계산 + if (ops[idx+1] == '+') s = nums[idx] + nums[idx+1]; + else if (ops[idx+1] == '-') s = nums[idx] - nums[idx+1]; + else s = nums[idx] * nums[idx+1]; + // 괄호 외부 계산 + if (ops[idx] == '+') t += s; + else if (ops[idx] == '-') t -= s; + else t *= s; + dfs(idx + 2, t); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + M = Integer.parseInt(br.readLine()) / 2; + char[] str = br.readLine().toCharArray(); + // 숫자, 연산자를 분리하여 배열에 저장 + nums = new int[M]; + ops = new char[M]; + for (int i = 0; i < M; i++) { + nums[i] = str[2*i+2] - '0'; + ops[i] = str[2*i+1]; + } + dfs(0, str[0] - '0'); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ13460.java" "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ13460.java" new file mode 100644 index 0000000..2c64af5 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ13460.java" @@ -0,0 +1,114 @@ +package bj; + +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 BJ13460 { + /* 17281. 구슬 탈출2 + 시뮬레이션 + [움직이는 최소 회수, 움직이는 회수는 10회 이하] => 4^10 => BFS + */ + final static int[] dr = {0, 0, -1, 1}; + final static int[] dc = {-1, 1, 0, 0}; + + public static int bfs(char[][] map, int bR, int bC, int rR, int rC){ + int result = -1; + int nbR, nbC, nrR, nrC, dep; + Queue q = new LinkedList<>(); + q.offer(new int[] {bR, bC, rR, rC, 0}); + int[] temp; + boolean red = false, blue = false; + + outer:while (!q.isEmpty()) { + temp = q.poll(); + dep = temp[4]; + if (dep >= 10) break; + for (int i = 0; i < dr.length; i++) { + nbR = temp[0]; nbC = temp[1]; + nrR = temp[2]; nrC = temp[3]; + red = false; blue = false; + // 빨간 구슬이 동일선상에서 파란 구슬보다 앞에 있는 경우 + if (Math.signum(nrR - nbR) == dr[i] && Math.signum(nrC - nbC) == dc[i]) { + // 빨간 구슬을 먼저 움직임 + while (map[nrR][nrC] == '.') { + nrR += dr[i]; nrC += dc[i]; + } + if (map[nrR][nrC] == '#') { + nrR -= dr[i]; nrC -= dc[i]; + map[nrR][nrC] = '#'; + } else { + nrR -= dr[i]; nrC -= dc[i]; + red = true; + } + // 파란 구슬을 움직임 + while (map[nbR][nbC] == '.') { + nbR += dr[i]; nbC += dc[i]; + } + if (map[nbR][nbC] == '#') { + nbR -= dr[i]; nbC -= dc[i]; + } else blue = true; + map[nrR][nrC] = '.'; + // 빨간 구슬과 파란 구슬의 구멍 도착 여부를 통해 다음 과정을 수행 + if (red && !blue) { + result = dep + 1; + break outer; + } else if (!red && !blue) + q.offer(new int[] {nbR, nbC, nrR, nrC, dep+1}); + } else { // 그렇지 않은 경우 + // 파란 구슬을 먼저 움직임 + while (map[nbR][nbC] == '.') { + nbR += dr[i]; nbC += dc[i]; + } + if (map[nbR][nbC] == '#') { + nbR -= dr[i]; nbC -= dc[i]; + map[nbR][nbC] = '#'; + } else { + nbR -= dr[i]; nbC -= dc[i]; + blue = true; + } + // 빨간 구슬을 움직임 + while (map[nrR][nrC] == '.') { + nrR += dr[i]; nrC += dc[i]; + } + if (map[nrR][nrC] == '#') { + nrR -= dr[i]; nrC -= dc[i]; + } else red = true; + map[nbR][nbC] = '.'; + // 빨간 구슬과 파란 구슬의 구멍 도착 여부를 통해 다음 과정을 수행 + if (red && !blue) { + result = dep + 1; + break outer; + } else if (!red && !blue) + q.offer(new int[] {nbR, nbC, nrR, nrC, dep+1}); + } + } + } + return result; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + char[][] map = new char[N][]; + int bR = 0, bC = 0, rR = 0, rC = 0; + for (int i = 0; i < N; i++) map[i] = br.readLine().toCharArray(); + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + if (map[i][j] == 'B') { + bR = i; bC = j; + map[i][j] = '.'; + } else if(map[i][j] == 'R') { + rR = i; rC = j; + map[i][j] = '.'; + } + } + } + System.out.println(bfs(map, bR, bC, rR, rC)); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ17281.java" "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ17281.java" new file mode 100644 index 0000000..b8d1d8d --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ17281.java" @@ -0,0 +1,90 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ17281 { + /* 17281. 야구 + 시뮬레이션 + [2 <= N <= 50, 선수 8명의 타순] => 8! * 50 => 순열 + */ + final static int MAX_M = 9; + static int[][] hitter; + static int N, result = 0; + + // 야구 시뮬레이션 + public static int calcScore(int[] arr) { + int idx = 0, cnt, score = 0; + int[] base = new int[MAX_M]; // 주자의 상태 + for (int i = 0; i < N; i++) { + cnt = 0; + Arrays.fill(base, 0); + while (cnt < 3) { // 3아웃 체인지 + switch (hitter[i][arr[idx]]) { + case 0: // 아웃 + cnt++; + break; + case 1: case 2: case 3: // 1,2,3루타 + int hit = hitter[i][arr[idx]]; + for (int j = 0; j < MAX_M; j++) { + if (base[j] > 0) { + if (base[j] + hit > 3) { + score++; + base[j] = 0; + } else base[j] += hit; + } + } + base[idx] = hit; + break; + case 4: // 홈련 + int runner = 1; + for (int j = 0; j < MAX_M; j++) if (base[j] > 0) runner++; + score += runner; + Arrays.fill(base, 0); + break; + } + idx = (idx+1)%MAX_M; // cyclic index + } + } + return score; + } + + // swap을 이용한 순열 + public static void simulate(int[] arr, int r) { + if (r == MAX_M) { + // 4번 타자 1번으로 고정 + swap(arr, 0, 3); + result = Math.max(result, calcScore(arr)); + swap(arr, 0, 3); + } + for (int i = r; i < MAX_M; i++) { + swap(arr, r, i); + simulate(arr, r+1); + swap(arr, r, i); + } + } + + public static void swap(int[] arr, int i, int j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + N = Integer.parseInt(br.readLine()); + hitter = new int[N][MAX_M]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < MAX_M; j++) hitter[i][j] = Integer.parseInt(st.nextToken()); + } + int[] arr = new int[MAX_M]; + for (int i = 0; i < MAX_M; i++) arr[i] = i; + simulate(arr, 1); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2110.java" "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2110.java" new file mode 100644 index 0000000..d6d3201 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2110.java" @@ -0,0 +1,42 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ2110 { + /* 2110. 공유기 설치 + 인접한 두 공유기 사이의 최대 거리를 기준으로 이분 탐색 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int C = Integer.parseInt(st.nextToken()); + int[] arr = new int[N]; + for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(br.readLine()); + Arrays.sort(arr); + int lef = 1, rig = arr[N-1] - arr[0], mid; + int cnt, prev, answer = 0; + while (lef <= rig) { + mid = (lef + rig) / 2; + cnt = 1; + // 현재 지정한 공유기 사이의 최대 거리가 주어진 집의 좌표에서 만족하는지 확인 + prev = arr[0]; + for (int i = 1; i < N; i++) { + if (arr[i] - prev >= mid) { + prev = arr[i]; + cnt++; + } + } + if (cnt >= C) { // 만족할 경우 lef를 현재 지정한 최대 거리 + 1로 설정 + lef = mid + 1; + answer = mid; // 현재 최대 거리가 만족하므로 저장 + } else rig = mid - 1; // 만족하지 않을 경우 rig를 현재 지정한 최대 거리 -1로 설정 + } + + System.out.println(answer); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2212.java" "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2212.java" new file mode 100644 index 0000000..0c64e3d --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/BJ2212.java" @@ -0,0 +1,34 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ2212 { + /* 2212. 센서 + 센서의 위치를 정렬 후 센서 사이의 거리가 큰 순으로 집중국의 수 - 1개의 좌표의 + 차이의 합을 구한다. + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int K = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + int[] arr = new int[N]; + for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); + if (N <= K) { + System.out.println(0); + return; + } + Arrays.sort(arr); // 센서의 위치 정렬 + int result = arr[N-1] - arr[0]; + int[] diff = new int[N-1]; + for (int i = 0; i < N-1; i++) diff[i] = arr[i+1] - arr[i]; + Arrays.sort(diff); // 센서 사이의 거리 정렬 + for (int i = 0; i < K-1; i++) result -= diff[N-2-i]; + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week19(220110)/PG64065.java" "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/PG64065.java" new file mode 100644 index 0000000..58a9508 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week19(220110)/PG64065.java" @@ -0,0 +1,40 @@ +package pg; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; + +public class PG64065 { + /* Level 2. 튜플 + 튜플 원소의 index = 전체 원소 개수 - 각 집합에서 존재하는 해당 원소 개수 => 해쉬 + */ + public static void main(String[] args) { + Solution test = new Solution(); + System.out.println(Arrays.toString(test.solution("{{2},{2,1},{2,1,3},{2,1,3,4}}"))); + System.out.println(Arrays.toString(test.solution("{{1,2,3},{2,1},{1,2,4,3},{2}}"))); + System.out.println(Arrays.toString(test.solution("{{20,111},{111}}"))); + System.out.println(Arrays.toString(test.solution("{{123}}"))); + System.out.println(Arrays.toString(test.solution("{{4,2,3},{3},{2,3,4,1},{2,3}}"))); + } + + static class Solution { + public int[] solution(String s) { + HashMap map = new HashMap<>(); + s = s.replaceAll("\\{",""); + s = s.replaceAll("\\}",""); + s = s.replaceAll("\\,"," "); + StringTokenizer st = new StringTokenizer(s); + int temp; + while (st.hasMoreElements()) { + temp = Integer.parseInt(st.nextToken()); + map.put(temp, map.getOrDefault(temp, 0) + 1); + } + int[] answer = new int[map.size()]; + for (Map.Entry entry:map.entrySet()) { + answer[map.size()-entry.getValue()] = entry.getKey(); + } + return answer; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week20(220117)/BJ2533.java" "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/BJ2533.java" new file mode 100644 index 0000000..e4e3a93 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/BJ2533.java" @@ -0,0 +1,46 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BJ2533 { + /* 2533. 사회망 서비스(SNS) + 다른 node와 연결된 개수가 가장 많은 node부터 선택하고 제거 => 시간초과 + 블로그 참조 DF S& DP: https://hqjang.tistory.com/104 + */ + public static void dfs(ArrayList[] nodeList, int[][] dp, int parent, boolean[] visited) { + visited[parent] = true; + dp[parent][0] = 1; + for (int child: nodeList[parent]) { + if (visited[child]) continue; + dfs(nodeList, dp, child, visited); + dp[parent][0] += Math.min(dp[child][0], dp[child][1]); // parent가 얼리어답터일 경우 + // child는 얼리어답터이어도 아니어도 됨 + dp[parent][1] += dp[child][0]; // 아닐 경우 + // child는 반드시 얼리어답터 + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + ArrayList[] nodeList = new ArrayList[N]; + for (int i = 0; i < N; i++) nodeList[i] = new ArrayList<>(); + int A, B; + for (int i = 0; i < N-1; i++) { + st = new StringTokenizer(br.readLine()); + A = Integer.parseInt(st.nextToken()) - 1; + B = Integer.parseInt(st.nextToken()) - 1; + nodeList[A].add(B); + nodeList[B].add(A); + } + int[][] DP = new int[N][2]; + boolean[] visited = new boolean[N]; + dfs(nodeList, DP, 0, visited); + System.out.println(Math.min(DP[0][0], DP[0][1])); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week20(220117)/PG17683.java" "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/PG17683.java" new file mode 100644 index 0000000..00b41b6 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/PG17683.java" @@ -0,0 +1,94 @@ +package pg; + +import java.text.SimpleDateFormat; +import java.util.Date; + +public class PG17683 { + /* Level 2. 방금그곡 + 문자열 다루기 + */ + public static void main(String[] args) throws Exception { + Solution test = new Solution(); + System.out.println(test.solution("ABCDEFG", new String[]{"12:00,12:14,HELLO,CDEFGAB", "13:00,13:05,WORLD,ABCDEF"})); + System.out.println(test.solution("CC#BCC#BCC#BCC#B", new String[]{"03:00,03:30,FOO,CC#B", "04:00,04:08,BAR,CC#BCC#BCC#B"})); + System.out.println(test.solution("ABC", new String[]{"12:00,12:14,HELLO,C#DEFGAB", "13:00,13:05,WORLD,ABCDEF"})); + System.out.println(test.solution("CC#BCC#BCC#", new String[]{"03:00,03:08,FOO,CC#B"})); + System.out.println(test.solution("A#", new String[]{"13:00,13:02,HAPPY,B#A#"})); + System.out.println(test.solution("CCB", new String[]{"03:00,03:10,FOO,CCB#CCB", "04:00,04:08,BAR,ABC"})); + } + + static class Music { + int startTime; + int playTime; + String title; + String score; + + public Music(int startTime, int playTime, String title, String score) { + this.startTime = startTime; + this.playTime = playTime; + this.title = title; + this.score = score; + } + + public int getStartTime() { + return startTime; + } + + public int getPlayTime() { + return playTime; + } + + public String getTitle() { + return title; + } + + public String getScore() { + return score; + } + } + + static class Solution { + public String solution(String m, String[] musicinfos) throws Exception { + Music[] musics = new Music[musicinfos.length]; + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); + for(int i = 0; i < musicinfos.length; i++) { + String[] str = musicinfos[i].split(","); + Date start = sdf.parse(str[0]); + Date end = sdf.parse(str[1]); + int playTime = (int) ((end.getTime() - start.getTime()) / (60 * 1000)); + StringBuilder temp = new StringBuilder(str[3]); + for (int j = 0; j < temp.length(); j++) + if (temp.charAt(j) == '#') temp.setCharAt(j - 1, (char) ('a' - 'A' + temp.charAt(j - 1))); + String tmp = temp.toString().replaceAll("#",""); + + temp = new StringBuilder(tmp); + for (int j = 0; j < Math.ceil((double) playTime / tmp.length()); j++) temp.append(tmp); + musics[i] = new Music((int) start.getTime(), playTime, str[2], temp.toString().substring(0, playTime)); + } +// for (Music music:musics) { +// System.out.println(music.getPlayTime()+" "+music.getTitle()+" "+music.getScore()); +// } + StringBuilder mm = new StringBuilder(m); + for (int j = 0; j < mm.length(); j++) + if (mm.charAt(j) == '#') mm.setCharAt(j - 1, (char) ('a' - 'A' + mm.charAt(j - 1))); + m = mm.toString().replaceAll("#",""); + int res = -1; + for(int i = 0; i < musics.length; i++) { + String temp = musics[i].getScore(); + int index = temp.indexOf(m); + if (index == -1) continue; + if (res != -1) { + if (musics[res].getPlayTime() < musics[i].getPlayTime()) { + res = i; + } else if (musics[res].getPlayTime() < musics[i].getPlayTime() && + musics[res].getStartTime() > musics[i].getStartTime()) { + res = i; + } + } else res = i; + } + + if (res == -1) return "(None)"; + return musics[res].getTitle(); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1062.java" "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1062.java" new file mode 100644 index 0000000..7c626bf --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1062.java" @@ -0,0 +1,63 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.StringTokenizer; + +public class bj1062 { + /* 1062. 가르침 + 조합,set => 시간초과 => 비트마스킹 + */ + public static int result = 0; + public static int[] chars; + public static HashSet totalChars; + + public static void comb(Integer[] tot, int sel, int n, int r, int s, int cnt){ + if (cnt == r) { + int count = 0; + sel = sel | 1 | (1 << ('n' - 'a')) | (1 << ('t' - 'a')) | (1 << ('c' - 'a')) | (1 << ('i' - 'a')); + for (int temp:chars) + if (temp == (temp & sel)) count++; // 조합을 통해 선택한 문자 set이 단어의 문자 set을 포함하는지 + result = Math.max(result, count); + return; + } + + for (int i = s; i < n; i++) { + sel = sel | (1 << tot[i]); + comb(tot, sel, n, r, i + 1, cnt + 1); + sel = sel ^ (1 << tot[i]); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()) - 5; + if (K < 0) { + System.out.println(0); + return; + } + chars = new int[N]; + totalChars = new HashSet<>(); + for (int i = 0; i < N; i++) { + String str = br.readLine(); + char[] word = str.substring(4, str.length() - 4).toCharArray(); + for (char ch:word) { + chars[i] = chars[i] | (1 << (ch - 'a')); // 각 단어에 포함된 문자 set + totalChars.add(ch - 'a'); // 단어들에 포함된 전체 문자 set + } + } + if (K >= totalChars.size()) { + System.out.println(N); + return; + } + + Integer[] tot = totalChars.toArray(new Integer[0]); + int sel = 0; + comb(tot, sel, totalChars.size(), K,0,0); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1300.java" "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1300.java" new file mode 100644 index 0000000..d789a76 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj1300.java" @@ -0,0 +1,32 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class bj1300 { + /* 1300. K번째 수 + K번째 수를 어떤 수로 가정하고 그 수를 기준으로 이분 탐색 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int K = Integer.parseInt(br.readLine()); + long lef = 1, rig = K, result = 0; + while (lef <= rig) { + long mid = (lef + rig) / 2; + long cnt = 0; + cnt += mid / N * N; + for (long i = mid / N + 1; i <= N; i++) { + cnt += (Math.min(mid / i, N)); + if (cnt > K) break; + } + if (cnt < K) lef = mid + 1; + else { + result = mid; + rig = mid - 1; + } + } + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj16234.java" "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj16234.java" new file mode 100644 index 0000000..32236a3 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week20(220117)/bj16234.java" @@ -0,0 +1,85 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class bj16234 { + /* 16234. 인구이동 + 시뮬레이션,DFS + */ + public static final int[] dr = {-1, 0, 1, 0}; + public static final int[] dc = {0, -1, 0, 1}; + + public static boolean isValid(int r, int c, int n) { + return r >= 0 && r < n && c >= 0 && c < n; + } + + public static void printMap(int[][] map, int n){ + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + System.out.print(map[i][j]+" "); + } + System.out.println(); + } + System.out.println(); + } + + public static int simulate(int n, int lef, int rig, int[][] map) { + int result = 0; + while(true) { + boolean[][] visited = new boolean[n][n]; // 날마다 방문 표시 + int count = 0; // 연합의 수 + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (visited[i][j]) continue; + ArrayList united = new ArrayList<>(); // 연합인 나라들의 좌표 + int sum = dfs(n, lef, rig, map, visited, united, i, j, 0); + if (united.size() > 1) { // 연합이 존재하면 + int val = sum / united.size(); + for (int[] contry:united) map[contry[0]][contry[1]] = val; + count++; + } + } + } +// printMap(map, n); +// System.out.println(count); + if (count == 0) break; // 인구 이동X + result++; // 날짜 카운트 + } + return result; + } + + public static int dfs(int n, int lef, int rig, int[][] map, boolean[][] visited, ArrayList united, + int r, int c, int sum) { + visited[r][c] = true; + united.add(new int[] {r, c}); + sum = map[r][c]; + for (int i = 0; i < dr.length; i++) { + int nr = r + dr[i]; + int nc = c + dc[i]; + if (isValid(nr, nc, n) && !visited[nr][nc]) { + int diff = Math.abs(map[r][c] - map[nr][nc]); + if (diff >= lef && diff <= rig) sum += dfs(n, lef, rig, map, visited, united, nr, nc, sum); + } + } + return sum; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int L = Integer.parseInt(st.nextToken()); + int R = Integer.parseInt(st.nextToken()); + int[][] map = new int[N][N]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < N; j++) + map[i][j] = Integer.parseInt(st.nextToken()); + } + System.out.println(simulate(N, L, R, map)); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ11085.java" "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ11085.java" new file mode 100644 index 0000000..49274ba --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ11085.java" @@ -0,0 +1,60 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BJ11085 { + /* 11085. 군사이동 + Dijkstra + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int p = Integer.parseInt(st.nextToken()); + int w = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + int c = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + ArrayList[] nodeList = new ArrayList[p]; + for (int i = 0; i < p; i++) nodeList[i] = new ArrayList<>(); + for (int i = 0; i < w; i++) { + st = new StringTokenizer(br.readLine()); + int A = Integer.parseInt(st.nextToken()); + int B = Integer.parseInt(st.nextToken()); + int D = Integer.parseInt(st.nextToken()); + nodeList[A].add(new int[]{B, D}); + nodeList[B].add(new int[]{A, D}); + } + + int[] width = new int[p]; + boolean[] visisted = new boolean[p]; + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o2[1], o1[1])); + + pq.offer(new int[]{c, 1000}); + while (!pq.isEmpty()){ + int[] cur = pq.poll(); +// System.out.println(Arrays.toString(cur)); +// System.out.println(Arrays.toString(width)); +// System.out.println(Arrays.toString(visisted)); + int index = cur[0]; + int val = cur[1]; + if (index == v) break; + if (visisted[index]) continue; + visisted[index] = true; + + for (int[] node:nodeList[index]) { + int temp = Math.min(val, node[1]); + if (width[node[0]] < temp) { + width[node[0]] = temp; + pq.offer(new int[]{node[0], temp}); + } + } + } + System.out.println(width[v]); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ1700.java" "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ1700.java" new file mode 100644 index 0000000..2c398fa --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ1700.java" @@ -0,0 +1,58 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1700 { + /* 1700. 멀티탭 스케줄링 + 구현 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + int[] arr = new int[K]; + for (int i = 0; i < K; i++) arr[i] = Integer.parseInt(st.nextToken()); + int[] plug = new int[N]; + int s = 0, e = 0; + outer:while (s < N && e < K) { + for (int i = 0; i < s; i++) + if (plug[i] == arr[e]) { + e++; + continue outer; + } + plug[s++] = arr[e++]; + } + int[] schedule = new int[K+1]; + for (int i = 1; i < K+1; i++) schedule[i] = K; + int result = 0; + + outer:for (int i = N; i < K; i++) { + for (int p:plug) + if (p == arr[i]) continue outer; + for (int p:plug) { + schedule[p] = K; + for (int k = i + 1; k < K; k++) + if (p == arr[k]) { + schedule[p] = k; + break; + } + } + + int index = 0, val = 0; + for (int j = 0; j < N; j++) + if (schedule[plug[j]] > val) { + val = schedule[plug[j]]; + index = j; + } + plug[index] = arr[i]; + result++; + } + + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ17136.java" "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ17136.java" new file mode 100644 index 0000000..9ad8b84 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ17136.java" @@ -0,0 +1,73 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ17136 { + /* 17136. 색종이 붙이기 + DFS + */ + public static int MAP_SIZE = 10; + public static int PAPER_MAX_SIZE = 5; + public static int PAPER_NUM = 5; + public static int[][] map; + public static int[] paper; + public static int result = Integer.MAX_VALUE; + + public static boolean doFilter(int r, int c, int n) { + if (r + n > MAP_SIZE || c + n > MAP_SIZE) return false; + for (int i = r; i < r + n; i++) + for (int j = c; j < c + n; j++) + if (map[i][j] == 0) return false; + return true; + } + + public static void doPaper(int r, int c, int n, int v) { + for (int i = r; i < Math.min(r + n, MAP_SIZE); i++) + for (int j = c; j < Math.min(c + n, MAP_SIZE); j++) + map[i][j] = v; + } + + public static void dfs(int r, int c, int cnt) { + if (r >= MAP_SIZE || c >= MAP_SIZE) { + result = Math.min(result, cnt); + return; + } + if (map[r][c] == 0) { + if (c + 1 < MAP_SIZE) dfs(r, c + 1, cnt); + else dfs(r + 1, 0, cnt); + return; + } + + for (int k = 1; k <= PAPER_MAX_SIZE; k++) { + if (r + k > MAP_SIZE || c + k > MAP_SIZE || paper[k] >= PAPER_NUM) continue; + if (doFilter(r, c, k)) { + doPaper(r, c, k, 0); + paper[k]++; + if (c + k < MAP_SIZE) dfs(r, c + k, cnt + 1); + else dfs(r + 1, 0, cnt + 1); + doPaper(r, c, k, 1); + paper[k]--; + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + map = new int[MAP_SIZE][MAP_SIZE]; + for (int i = 0; i < MAP_SIZE; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < MAP_SIZE; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + paper = new int[PAPER_NUM+1]; + dfs(0, 0, 0); + + if (result == Integer.MAX_VALUE) System.out.println(-1); + else System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ4811.java" "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ4811.java" new file mode 100644 index 0000000..9e3062b --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/BJ4811.java" @@ -0,0 +1,29 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ4811 { + /* 4811. 알약 + N <= 30 => 30C15 >= 10^8 => DP + */ + public static final int MAX_NUM = 30; + + public static void main(String[] args) throws IOException { + long[][] DP = new long[MAX_NUM+1][MAX_NUM+1]; + for (int i = 1; i < MAX_NUM+1; i++) DP[0][i] = 1; + for (int i = 1; i < MAX_NUM+1; i++) { + for (int j = i; j < MAX_NUM+1; j++) { + DP[i][j] = DP[i-1][j] + DP[i][j-1]; + } + } + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + while (true) { + int N = Integer.parseInt(br.readLine()); + if (N == 0) break; + System.out.println(DP[N][N]); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week21(220124)/PG17686.java" "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/PG17686.java" new file mode 100644 index 0000000..9c328c0 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week21(220124)/PG17686.java" @@ -0,0 +1,73 @@ +package pg; + +import java.util.*; + +public class PG17686 { + /* Level 2. 파일명 정렬 + 정렬 + */ + + public static void main(String[] args) { + PG17686.Solution test = new PG17686.Solution(); + System.out.println(Arrays.toString(test.solution(new String[]{"img12.png", "img10.png", "img02.png", "img1.png", "IMG01.GIF", "img2.JPG"}))); + System.out.println(Arrays.toString(test.solution(new String[]{"F-5 Freedom Fighter", "B-50 Superfortress", "A-10 Thunderbolt II", "F-14 Tomcat"}))); + } + + static class File { + String head; + int number; + int tail; + public File(String head, int number, int tail) { + this.head = head; + this.number = number; + this.tail = tail; + } + } + + static class Solution { + public String[] solution(String[] files) { + ArrayList fileList = new ArrayList<>(); + for (int i = 0; i < files.length; i++) { + String head; + int number; + String str = files[i]; + int s = 0, e = str.length(); + for (int j = 0; j < str.length(); j++) { + if (str.charAt(j) >= '0' && str.charAt(j) <= '9') { + s = j; + break; + } + } + for (int j = s; j < str.length(); j++) { + if (!(str.charAt(j) >= '0' && str.charAt(j) <= '9')) { + e = j; + break; + } + } + head = str.substring(0, s).toLowerCase(); + number = Integer.parseInt(str.substring(s, e)); + fileList.add(new File(head, number, i)); + } + +// for (File f:fileList) { +// System.out.println(f.head+" "+f.number+" "+f.tail); +// } + + fileList.sort(new Comparator() { + @Override + public int compare(File o1, File o2) { + int res = o1.head.compareTo(o2.head); + if (res != 0) return res; + res = Integer.compare(o1.number, o2.number); + if (res != 0) return res; + return Integer.compare(o1.tail, o2.tail); + } + }); + + String[] result = new String[files.length]; + for (int i = 0; i < fileList.size(); i++) + result[i] = files[fileList.get(i).tail]; + return result; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1043.java" "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1043.java" new file mode 100644 index 0000000..f38a629 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1043.java" @@ -0,0 +1,68 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class BJ1043 { + /* 1043. 거짓말 + union-find + */ + public static void union(int[] p, int a, int b) { + int pA = find(p, a); + int pB = find(p, b); + if (pA != pB) { + if (pB < pA) { + int temp = pB; + pB = pA; + pA = temp; + } + p[pA] += p[pB]; + p[pB] = pA; + } + } + + public static int find(int[] p, int n) { + if (p[n] < 0) return n; + return p[n] = find(p, p[n]); + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + // 사람의 수, 파티의 수 + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int[] parent = new int[N+1]; + for (int i = 0; i < N+1; i++) parent[i] = -1; + // 진실을 아는 사람 + st = new StringTokenizer(br.readLine()); + int p = Integer.parseInt(st.nextToken()); + for (int i = 0; i < p; i++) { + int j = Integer.parseInt(st.nextToken()); + union(parent, 0, j); + } + // 각 파티마다 오는 사람 + long[] party = new long[M]; + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + int t = Integer.parseInt(st.nextToken()); + int q = Integer.parseInt(st.nextToken()); + party[i] = 1L << q; + for (int j = 0; j < t - 1; j++) { + int r = Integer.parseInt(st.nextToken()); + union(parent, q, r); + party[i] = party[i] | (1L << r); + } + } + // 파티의 최댓값 + int result = 0; + long T = 0; + for (int i = 1; i < N+1; i++) + if (find(parent, i) == 0) T = T | (1L << i); + for (int i = 0; i < M; i++) + if ((T & party[i]) == 0) result += 1; + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1194.java" "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1194.java" new file mode 100644 index 0000000..7a04fca --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/BJ1194.java" @@ -0,0 +1,73 @@ +package bj; + +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 BJ1194 { + /* 1194. 달이 차오른다, 가자. + BFS(3차원) + */ + private static final int[] dr = {-1, 0, 1, 0}; + private static final int[] dc = {0, 1, 0, -1}; + + public static boolean isValid(int r, int c, int n, int m) { + return r >= 0 && r < n && c >= 0 && c < m; + } + + public static int bfs(char[][] maze, int[][][] map, int n, int m) { + Queue q = new LinkedList<>(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < m; j++) { + if (maze[i][j] == '0') { + q.offer(new int[]{0, i, j}); + map[0][i][j] = 1; + } + } + } + + int nr, nc, k, d; + int[] p; + char next; + while (!q.isEmpty()) { + p = q.poll(); + k = p[0]; + d = map[k][p[1]][p[2]]; + for (int i = 0; i < dr.length; i++) { + nr = p[1] + dr[i]; nc = p[2] + dc[i]; + if (!isValid(nr, nc, n, m) || map[k][nr][nc] != 0) continue; + next = maze[nr][nc]; + if (next == '.' || next == '0') { + q.offer(new int[]{k, nr, nc}); + map[k][nr][nc] = d + 1; + } else if (next == '#') { + continue; + } else if (next >= 'a' && next <= 'f') { + q.offer(new int[] {k | (1 << next - 'a'), nr, nc}); + map[k | (1 << next - 'a')][nr][nc] = d + 1; + } else if (next >= 'A' && next <= 'F') { + if (((1 << next - 'A') & k) != 0) q.offer(new int[] {k, nr, nc}); + map[k][nr][nc] = d + 1; + } else if (next == '1') { + return d; + } + } + } + return -1; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + char[][] maze = new char[N][]; + int[][][] map = new int[(1 << 6)][N][M]; + for (int i = 0; i < N; i++) + maze[i] = br.readLine().toCharArray(); + System.out.println(bfs(maze, map, N, M)); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG42842.java" "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG42842.java" new file mode 100644 index 0000000..d149e6a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG42842.java" @@ -0,0 +1,23 @@ +package pg; + +import java.util.Arrays; + +public class PG42842 { + /* Level 2. 카펫 + brown => m + n, yellow => mn, 2차 방정식 + */ + public static void main(String[] args) { + PG42842.Solution test = new PG42842.Solution(); + System.out.println(Arrays.toString(test.solution(10, 2))); + System.out.println(Arrays.toString(test.solution(8, 1))); + System.out.println(Arrays.toString(test.solution(24, 24))); + } + + static class Solution { + public int[] solution(int brown, int yellow) { + int s = (brown + 4) / 2; + int p = yellow + brown; + return new int[]{(int) (s + Math.sqrt(s * s - 4 * p)) / 2, (int) (s - Math.sqrt(s * s - 4 * p)) / 2}; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG43238.java" "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG43238.java" new file mode 100644 index 0000000..59abccf --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG43238.java" @@ -0,0 +1,39 @@ +package pg; + +import java.util.Arrays; +import java.util.stream.Stream; + +public class PG43238 { + /* Level 3. 입국심사 + 이분탐색 -> 심사를 받는데 걸리는 시간이 기준 -> 전체 걸리는 시간을 각 심사관이 심사를 하는데 걸리는 + 시간으로 나누고 그 값들을 합하여 기다리는 사람 수보다 많은지를 확인 + */ + public static void main(String[] args) { + PG43238.Solution test = new PG43238.Solution(); + System.out.println(test.solution(6, new int[] {7, 10})); + System.out.println(test.solution(6, new int[] {3, 4, 5})); + } + + static class Solution { + public long solution(int n, int[] times) { + long lef = 0; + long rig = (long) Arrays.stream(times).max().getAsInt() * n; + long mid = 0; + long m = 0; + + while (lef + 1 != rig) { + mid = (lef + rig) / 2; + m = 0; + for (int time : times) { + m += mid / time; + } + if (m < n) { + lef = mid; + } else { + rig = mid; + } + } + return rig; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG84021.java" "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG84021.java" new file mode 100644 index 0000000..452f475 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week23(220221)/PG84021.java" @@ -0,0 +1,129 @@ +package pg; + +import java.util.ArrayList; + +public class PG84021 { + /* Level 3. 퍼즐 조각 채우기 + 시뮬레이션 + */ + private static final int[] dr = {0, 1, 0, -1}; + private static final int[] dc = {1, 0, -1, 0}; + + public static void main(String[] args) { + PG84021.Solution test = new PG84021.Solution(); +// System.out.println(test.solution(new int[][] {{1,1,0,0,1,0},{0,0,1,0,1,0},{0,1,1,0,0,1},{1,1,0,1,1,1},{1,0,0,0,1,0},{0,1,1,1,0,0}}, +// new int[][] {{1,0,0,1,1,0},{1,0,1,0,1,0},{0,1,1,0,1,1},{0,0,1,0,0,0},{1,1,0,1,1,0},{0,1,0,0,0,0}})); +// System.out.println(test.solution(new int[][] {{0,0,0},{1,1,0},{1,1,1}}, new int[][] {{1,1,1},{1,0,0},{0,0,0}})); + System.out.println(test.solution(new int[][] {{0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 0}, {1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1}, {0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1}, {0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0}, {1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1}, {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0}}, + new int[][] {{1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1}, {1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1}, {1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0}, {1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, {1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1}, {1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1}, {1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1}, {1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1}})); + } + + static class Piece { + ArrayList coords = new ArrayList<>(); + } + + public static boolean isValid(int r, int c, int n) { + return r >= 0 && r < n && c >= 0 && c < n; + } + + public static void printPieces(ArrayList pieces) { + for (Piece piece:pieces) printPiece(piece); + } + + public static void printPiece(Piece piece) { + for (int[] coord:piece.coords) + System.out.print("("+coord[0]+","+coord[1]+"), "); + System.out.println(); + } + + public static void dfs(int r, int c, int n, int val, int[][] map, ArrayList el) { + el.add(new int[] {r, c}); + map[r][c] = 1 - val; + int nr, nc; + for (int i = 0; i < dr.length; i++) { + nr = r + dr[i]; nc = c + dc[i]; + if (isValid(nr, nc, n) && map[nr][nc] == val) { + dfs(nr, nc, n, val, map, el); + } + } + } + + public static ArrayList boardInit(int[][] board, int val) { + ArrayList pieces = new ArrayList<>(); + int n = board.length; + Piece tmp; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == val) { + tmp = new Piece(); + dfs(i, j, n, val, board, tmp.coords); + pieces.add(tmp); + } + } + } + return pieces; + } + + public static int[][] copyMap(int[][] map, int n) { + int[][] mapCopy = new int[n][n]; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + mapCopy[i][j] = map[i][j]; + return mapCopy; + } + + public static int[][] rotateMap(int[][] map, int n) { + int[][] mapRotate = new int[n][n]; + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + mapRotate[n-1-j][i] = map[i][j]; + return mapRotate; + } + + public static int playPuzzle(int[][] game_board, int[][] table) { + ArrayList gameBoardPieces = boardInit(game_board, 0); + ArrayList temp; + ArrayList gCoords, tCoords; + int n = game_board.length; + int count = 0, rd, cd; + int[] gCoord, tCoord; + ArrayList gRemove; + for (int i = 0; i < 4; i++) { + temp = boardInit(copyMap(table, n), 1); + gRemove = new ArrayList<>(); + for (Piece gPiece:gameBoardPieces) { + outer:for (Piece tPiece:temp) { + if (gPiece.coords.size() == tPiece.coords.size()) { + gCoords = gPiece.coords; tCoords = tPiece.coords; + rd = gCoords.get(0)[0] - tCoords.get(0)[0]; + cd = gCoords.get(0)[1] - tCoords.get(0)[1]; +// System.out.print("g:"); printPiece(gPiece); +// System.out.print("t:"); printPiece(tPiece); +// System.out.println("rd:"+rd+", "+"cd:"+cd); + for (int j = 0; j < gPiece.coords.size(); j++) { + gCoord = gCoords.get(j); tCoord = tCoords.get(j); + if (gCoord[0] != tCoord[0] + rd || gCoord[1] != tCoord[1] + cd) continue outer; + } + gRemove.add(gPiece); + for (int[] coord:tPiece.coords) table[coord[0]][coord[1]] = 0; + temp.remove(tPiece); + count += gPiece.coords.size(); + break; + } + } + } + for (Piece g:gRemove) gameBoardPieces.remove(g); + table = rotateMap(table, n); + } + return count; + } + + static class Solution { + public int solution(int[][] game_board, int[][] table) { +// ArrayList gameBoardPieces = boardInit(game_board); +// ArrayList tablePieces = boardInit(table); +// printPieces(gameBoardPieces); + return playPuzzle(game_board, table); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ20055.java" "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ20055.java" new file mode 100644 index 0000000..26474ec --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ20055.java" @@ -0,0 +1,55 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BJ20055 { + /* 20055. 컨베이어 벨트 위의 로봇 + 시뮬레이션 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + int[] A = new int[2*N]; + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < 2*N; i++) + A[i] = Integer.parseInt(st.nextToken()); + int up = 0, down = N-1, zero = 0, step = 1, pre, loc, next; + ArrayList robot = new ArrayList<>(); + while (true) { + if (--up < 0) up += (2 * N); + if (--down < 0) down += (2 * N); + for (int i = 0; i < robot.size(); i++) { + if (robot.get(i) == down) robot.remove(i--); + } + pre = -1; + for (int i = 0; i < robot.size(); i++) { + loc = robot.get(i); + next = (loc + 1) % (2 * N); + if (pre != next && A[next] >= 1) { + if (--A[next] == 0) zero++; + if (next == down) { + robot.remove(i--); + continue; + } + robot.set(i, next); + pre = next; + }else pre = loc; + } + + if (A[up] >= 1) { + if (--A[up] == 0) zero++; + robot.add(up); + } + + if (zero >= K) break; + step++; + } + System.out.println(step); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ2616.java" "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ2616.java" new file mode 100644 index 0000000..0e02c6e --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/BJ2616.java" @@ -0,0 +1,51 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ2616 { + /* 2616. 소형기관차 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + int[] arr = new int[N]; + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(st.nextToken()); + } + int M = Integer.parseInt(br.readLine()); + + int[] train = new int[N-M+1]; + int temp = 0; + for (int i = 0; i < M; i++) temp += arr[i]; + train[0] = temp; + for (int i = 0; i < N-M; i++) { + temp -= arr[i]; + temp += arr[i+M]; + train[i+1] = temp; + } + + int[][] DP = new int[3][N-M+1]; + for (int i = 0; i < 3; i++) { + for (int j = i*M; j < N+1+(i-3)*M; j++) { + if (i > 0) { + DP[i][j] = Math.max(DP[i][j-1], DP[i-1][j-M] + train[j]); + }else if (j > 0) { + DP[i][j] = Math.max(DP[i][j-1], train[j]); + }else DP[i][j] = train[0]; + } + } +// for (int i = 0; i < 3; i++) { +// for (int j = 0; j < N-M+1; j++) { +// System.out.print(DP[i][j] + " "); +// } +// System.out.println(); +// } + System.out.println(DP[2][N-M]); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG42885.java" "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG42885.java" new file mode 100644 index 0000000..43af3c5 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG42885.java" @@ -0,0 +1,32 @@ +package pg; + +import java.util.Arrays; + +public class PG42885 { + /* Level 2. 구명보트 + 투포인터 + */ + public static void main(String[] args) { + PG42885.Solution test = new PG42885.Solution(); + System.out.println(test.solution(new int[] {70, 50, 80, 50}, 100)); + System.out.println(test.solution(new int[] {70, 80, 50}, 100)); + } + + static class Solution { + public int solution(int[] people, int limit) { + int answer = 0; + int lef = 0, rig = people.length - 1; + Arrays.sort(people); + while (lef <= rig) { + if (people[lef] > limit / 2) { + answer += (rig - lef + 1); + break; + } + if (people[lef] + people[rig] <= limit) lef += 1; + rig -= 1; + answer += 1; + } + return answer; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG67259.java" "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG67259.java" new file mode 100644 index 0000000..75a1a87 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG67259.java" @@ -0,0 +1,57 @@ +package pg; + +import java.util.*; + +public class PG67259 { + /* Level 3. 경주로 건설 + BFS + 3차원 배열 + */ + public static void main(String[] args) { + PG67259.Solution test = new PG67259.Solution(); + System.out.println(test.solution(new int[][] {{0,0,0},{0,0,0},{0,0,0}})); + System.out.println(test.solution(new int[][] {{0,0,0,0,0,0,0,1},{0,0,0,0,0,0,0,0},{0,0,0,0,0,1,0,0},{0,0,0,0,1,0,0,0},{0,0,0,1,0,0,0,1},{0,0,1,0,0,0,1,0},{0,1,0,0,0,1,0,0},{1,0,0,0,0,0,0,0}})); + System.out.println(test.solution(new int[][] {{0,0,1,0},{0,0,0,0},{0,1,0,1},{1,0,0,0}})); + System.out.println(test.solution(new int[][] {{0,0,0,0,0,0},{0,1,1,1,1,0},{0,0,1,0,0,0},{1,0,0,1,0,1},{0,1,0,0,0,1},{0,0,0,0,0,0}})); + System.out.println(test.solution(new int[][] {{0, 0, 1, 0, 1, 1, 0, 0, 0, 0},{0, 0, 0, 0, 1, 0, 1, 1, 0, 1},{1, 0, 0, 0, 0, 1, 1, 0, 1, 0},{0, 0, 0, 0, 0, 0, 1, 0, 0, 0},{0, 0, 0, 0, 1, 0, 1, 0, 1, 1}, + {0, 0, 1, 0, 1, 1, 0, 1, 0, 1},{0, 1, 0, 0, 1, 0, 0, 0, 1, 0},{1, 0, 0, 1, 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 1, 0, 1, 0, 0},{1, 0, 0, 0, 0, 0, 0, 0, 1, 0}})); + } + + static final int[] dr = {0,1,0,-1}; + static final int[] dc = {1,0,-1,0}; + + static boolean isValid(int r, int c, int n) { + return r >= 0 && r < n && c >= 0 && c < n; + } + + static class Solution { + public int solution(int[][] board) { + int n = board.length; + boolean[][][] visited = new boolean[n][n][dr.length]; + visited[0][0][0] = visited[0][0][1] = visited[0][0][2] = visited[0][0][3] = true; + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[3])); + + pq.offer(new int[] {0, 0, -1, 0}); + int[] p; + int r, c, rc, dist = 0, nr, nc, cost; + + while (!pq.isEmpty()) { + p = pq.poll(); + r = p[0]; c = p[1]; rc = p[2]; dist = p[3]; + if (r == n-1 && c == n-1) break; + for (int i = 0; i < dr.length; i++) { + nr = r + dr[i]; nc = c + dc[i]; + if (isValid(nr, nc, n) && board[nr][nc] != 1) { + cost = dist + 100; + if (rc != -1 && (rc + i) % 2 == 1) cost += 500; + if (!visited[nr][nc][i] || cost <= board[nr][nc]) { + pq.offer(new int[] {nr, nc, i, cost}); + visited[nr][nc][i] = true; + board[nr][nc] = cost; + } + } + } + } + return dist; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG72411.java" "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG72411.java" new file mode 100644 index 0000000..1227c63 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week24(220228)/PG72411.java" @@ -0,0 +1,90 @@ +package pg; + +import java.util.*; +import java.util.stream.Collectors; + +public class PG72411 { + /* Level 2. 메뉴 리뉴얼 + */ + public static void main(String[] args) { + PG72411.Solution test = new PG72411.Solution(); + System.out.println(Arrays.toString(test.solution(new String[] {"ABCFG", "AC", "CDE", "ACDE", "BCFG", "ACDEH"}, new int[] {2, 3, 4}))); + System.out.println(Arrays.toString(test.solution(new String[] {"ABCDE", "AB", "CD", "ADE", "XYZ", "XYZ", "ACD"}, new int[] {2, 3, 5}))); + System.out.println(Arrays.toString(test.solution(new String[] {"XYZ", "XWY", "WXA"}, new int[] {2, 3, 4}))); + } + + static class Solution { + static final int ALPHABET = 'Z' - 'A' + 1; + static HashMap menus = new HashMap<>(); + + static class Menu { + String component; + int number; + public Menu(String component, int number) { + this.component = component; + this.number = number; + } + } + + public void combination(char[] orig, char[] sel, int n, int r, int s, int cnt) { + if (cnt == r) { + String key = new String(sel); + menus.put(key, menus.getOrDefault(key, 0) + 1); + return; + } + for (int i = s; i < n; i++) { + sel[cnt] = orig[i]; + combination(orig, sel, n, r, i + 1, cnt + 1); + } + } + + public char[] sortAlphabetString(String str){ + char[] charArray = new char[str.length()]; + int temp = 0, j = 0; + for (int i = 0; i < str.length(); i++) + temp = temp | (1 << (str.charAt(i) - 'A')); + for (int i = 0; i < ALPHABET; i++) + if ((temp & (1 << i)) != 0) charArray[j++] = (char) ('A' + i); + return charArray; + } + + public String[] solution(String[] orders, int[] course) { + char[] orderArray, comb; + List menuList; + int maxVal; + ArrayList answer = new ArrayList<>(); + for (int r:course) { + comb = new char[r]; + for (String order:orders) { + orderArray = sortAlphabetString(order); + combination(orderArray, comb, orderArray.length, r, 0, 0); + } + if (menus.isEmpty()) continue; +// for (Map.Entry entry:menus.entrySet()) +// System.out.println(entry.getKey() + " " + entry.getValue()); + menuList = menus.entrySet().stream().map(o -> new Menu(o.getKey(), o.getValue())).collect(Collectors.toList()); + menuList.sort((o1, o2) -> Integer.compare(o2.number, o1.number)); + maxVal = menuList.get(0).number; + if (maxVal < 2) continue; + for (Menu menu : menuList) + if (menu.number == maxVal) answer.add(menu.component); + else break; + menus.clear(); + } + answer.sort(new Comparator() { + @Override + public int compare(String o1, String o2) { + int len = Math.min(o1.length(), o2.length()); + for (int i = 0; i < len; i++) { + if (o1.charAt(i) < o2.charAt(i)) return -1; + else if (o1.charAt(i) > o2.charAt(i)) return 1; + } + if (o1.length() < o2.length()) return -1; + else if (o1.length() > o2.length()) return 1; + return 0; + } + }); + return answer.toArray(new String[0]); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week25(220307)/BJ1107.java" "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/BJ1107.java" new file mode 100644 index 0000000..deb353e --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/BJ1107.java" @@ -0,0 +1,55 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1107 { + /* 1107. 리모컨 + 백트래킹 + */ + private static int N; + private static int M; + private static int K; + private static int[] units; + private static boolean[] num = new boolean[10]; + private static int result; + + public static void dfs(int depth, int count, int channel) { + if (depth == 0) { + result = Math.min(result, count + Math.abs(N - channel)); + return; + } + for (int i = 0; i < 10; i++) { + // 리모컨의 아무 버튼도 누르지 않고 자리수를 내림 + if (depth != 1 && channel == 0) dfs(depth-1, count, channel); + if (!num[i]) { + if (i != 0 || depth == 1 || channel != 0) { + // 백트래킹 + if (channel > N && count + channel - N >= result) continue; + dfs(depth-1, count+1, channel+i*units[depth]); + }else dfs(depth-1, count, channel); // 0을 누를 수 있을 때 아무 버튼도 누르지 않고 자리수를 내림 + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + String str = br.readLine(); + K = str.length() + 1; + units = new int[K+1]; + units[1] = 1; + for (int i = 2; i < K+1; i++) units[i] = units[i-1] * 10; + N = Integer.parseInt(str); + result = Math.abs(N-100); + M = Integer.parseInt(br.readLine()); + if (M != 0) { + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < M; i++) num[Integer.parseInt(st.nextToken())] = true; + } + dfs(K, 0, 0); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG42578.java" "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG42578.java" new file mode 100644 index 0000000..8681522 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG42578.java" @@ -0,0 +1,32 @@ +package pg; + +import java.util.HashMap; + +public class PG42578 { + /* Level 2. 위장 + 해쉬 + */ + public static void main(String[] args) { + PG42578.Solution test = new PG42578.Solution(); + System.out.println(test.solution(new String[][] { + {"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"} + })); + System.out.println(test.solution(new String[][] { + {"crowmask", "face"}, {"bluesunglasses", "face"}, {"smoky_makeup", "face"} + })); + } + + static class Solution { + public int solution(String[][] clothes) { + int answer = 1; + HashMap map = new HashMap<>(); + for (String[] cloth:clothes) { + map.put(cloth[1], map.getOrDefault(cloth[1], 1)+1); + } + + for (int n: map.values()) + answer *= n; + return answer - 1; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG92343.java" "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG92343.java" new file mode 100644 index 0000000..03972c2 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week25(220307)/PG92343.java" @@ -0,0 +1,54 @@ +package pg; + +public class PG92343 { + /* Level 3. 양과 늑대 + 완전탐색 + */ + public static void main(String[] args) { + PG92343.Solution test = new PG92343.Solution(); + System.out.println(test.solution(new int[] {0,0,1,1,1,0,1,0,1,0,1,1}, new int[][] { + {0,1},{1,2},{1,4},{0,8},{8,7},{9,10},{9,11},{4,3},{6,5},{4,6},{8,9} + })); + System.out.println(test.solution(new int[] {0,1,0,1,1,0,1,0,0,1,0}, new int[][] { + {0,1},{0,2},{1,3},{1,4},{2,5},{2,6},{3,7},{4,8},{6,9},{9,10} + })); + } + + static class Solution { + + private static int N; + private static int result = 0; + + public void dfs(int[] info, int[][] tree, int parent, int sheep, int wolf, boolean[] visited) { + if (info[parent] == 0) sheep++; + else wolf++; + if (sheep <= wolf) return; +// System.out.println(parent+" "+sheep+" "+wolf); + result = Math.max(result, sheep); + visited[parent] = false; + if (tree[parent][0] != 0) { + visited[tree[parent][0]] = true; + if (tree[parent][1] != 0) + visited[tree[parent][1]] = true; + } + for (int i = 1; i < N; i++) { + if (visited[i]) { + dfs(info, tree, i, sheep, wolf, visited.clone()); + } + } + } + + public int solution(int[] info, int[][] edges) { + N = info.length; + int[][] tree = new int[N][2]; + int p, c; + for (int[] edge : edges) { + p = edge[0]; c = edge[1]; + if (tree[p][0] == 0) tree[p][0] = c; + else tree[p][1] = c; + } + dfs(info, tree, 0, 0, 0, new boolean[N]); + return result; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ15684.java" "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ15684.java" new file mode 100644 index 0000000..f58ac8c --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ15684.java" @@ -0,0 +1,84 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.StringTokenizer; + +public class BJ15684 { + /* 15684. 사다리 조작 + 시뮬레이션 + */ + static int N, M, H, result = 4; + static boolean[][] map; + + public static boolean simulate(boolean[][] map) { + int idx; + for (int i = 0; i < N; i++) { + idx = i; + for (int j = 0; j < H; j++) { + if (idx > 0 && map[idx-1][j]) idx--; + else if (idx < N-1 && map[idx][j]) idx++; + } + if (idx != i) return false; + } + return true; + } + + public static void combination(int[] arr, int[] tar, int n, int r, int s, int cnt) { + if (result == r) return; + if (r == cnt) { + int p, q; + for (int i = 0; i < r; i++) { + p = tar[i]/H; + q = tar[i]%H; + map[p][q] = true; + } + if (simulate(map)) result = r; + + for (int i = 0; i < r; i++) { + p = tar[i]/H; + q = tar[i]%H; + map[p][q] = false; + } + return; + } + for (int i = s; i < n; i++) { + tar[cnt] = arr[i]; + combination(arr, tar, n, r, i+1, cnt+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()); + M = Integer.parseInt(st.nextToken()); + H = Integer.parseInt(st.nextToken()); + map = new boolean[N-1][H]; + int a, b; + HashSet set = new HashSet<>(); + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + a = Integer.parseInt(st.nextToken())-1; + b = Integer.parseInt(st.nextToken())-1; + map[b][a] = true; + set.add(b*H+a); + } + + int[] arr = new int[(N-1)*H-M]; + int cnt = 0; + for (int i = 0; i < (N-1)*H; i++) { + if (set.contains(i)) continue; + arr[cnt++] = i; + } + for (int i = 0; i < 4; i++) { + if (i > result) break; + combination(arr, new int[i], (N-1)*H-M, i, 0, 0); + } + + if (result > 3) System.out.println(-1); + else System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ2075.java" "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ2075.java" new file mode 100644 index 0000000..9fc0764 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/BJ2075.java" @@ -0,0 +1,42 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +public class BJ2075 { + /* 2075. N번째 큰 수 + 우선순위 큐 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int[][] map = new int[N][N]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < N; j++) + map[i][j] = Integer.parseInt(st.nextToken()); + } + + PriorityQueue pq = new PriorityQueue<>(); + for (int i = 0; i < N; i++) + pq.offer(map[N-1][i]); + int result = pq.peek(); + + + for (int i = N-2; i >= 0; i--) { + for (int j = 0; j < N; j++) { + if (pq.peek() < map[i][j]) { + pq.poll(); + pq.offer(map[i][j]); + } + } + if (result == pq.peek()) break; + result = pq.peek(); + } + System.out.println(result); + } +} \ No newline at end of file diff --git "a/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG42626.java" "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG42626.java" new file mode 100644 index 0000000..9e9a664 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG42626.java" @@ -0,0 +1,33 @@ +package pg; + +import java.util.PriorityQueue; + +public class PG42626 { + /* Level 2. 더맵게 + 우선순위 큐 + */ + public static void main(String[] args) { + PG42626.Solution test = new PG42626.Solution(); + System.out.println(test.solution(new int[] {1, 2, 3, 9, 10, 12}, 7)); + } + + static class Solution { + public int solution(int[] scoville, int K) { + int answer = 0; + int N = scoville.length; + PriorityQueue pq = new PriorityQueue<>(); + for (int elem:scoville) pq.offer(elem); + + int p, q; + for (int i = 0; i < N-1; i++) { + if (pq.peek() >= K) break; + p = pq.poll(); + q = pq.poll(); + pq.add(p + 2 * q); + answer++; + } + if (pq.peek() < K) answer = -1; + return answer; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92342.java" "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92342.java" new file mode 100644 index 0000000..cdf55af --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92342.java" @@ -0,0 +1,58 @@ +package pg; + +import java.util.Arrays; + +public class PG92342 { + /* Level 2. 양궁대회 + DFS + */ + public static void main(String[] args) { + PG92342.Solution test = new PG92342.Solution(); + System.out.println(Arrays.toString(test.solution(5, new int[] {2,1,1,1,0,0,0,0,0,0,0}))); + System.out.println(Arrays.toString(test.solution(1, new int[] {1,0,0,0,0,0,0,0,0,0,0}))); + System.out.println(Arrays.toString(test.solution(9, new int[] {0,0,1,2,0,1,1,1,1,1,1}))); + System.out.println(Arrays.toString(test.solution(10, new int[] {0,0,0,0,0,0,0,0,3,4,3}))); + } + + static class Solution { + static int N = 10; + static int M = 0; + static int[] answer; + + public void dfs(int[] info, int dep, int cnt, int[] arr) { + if (cnt == 0) { + int ryon = 0; + int apeach = 0; + for (int i = 0; i < N; i++) { + if (info[i] == arr[i] && info[i] == 0) continue; + if (info[i] < arr[i]) ryon += 10-i; + else apeach += 10-i; + } + if (ryon > apeach && ryon-apeach >= M) { + if (answer.length == N+1 && ryon-apeach == M) { + for (int i = N; i >= 0; i--) { + if (answer[i] > arr[i]) return; + else if (answer[i] < arr[i]) break; + } + } + answer = arr.clone(); + M = ryon-apeach; + } + return; + } + if (dep > N) return; + + for (int i = 0; i <= cnt; i++) { + arr[dep] = i; + dfs(info, dep+1, cnt-i, arr); + arr[dep] = 0; + } + } + + public int[] solution(int n, int[] info) { + answer = new int[] {-1}; + dfs(info, 0, n, new int[N+1]); + return answer; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92344.java" "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92344.java" new file mode 100644 index 0000000..500ccba --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week26(220314)/PG92344.java" @@ -0,0 +1,51 @@ +package pg; + +import java.util.PriorityQueue; + +public class PG92344 { + /* Level 3. 파괴되지 않은 건물 + imos법 + [1] https://driip.me/65d9b58c-bf02-44bf-8fba-54d394ed21e0 + [2] https://imoz.jp/algorithms/imos_method.html + */ + public static void main(String[] args) { + PG92344.Solution test = new PG92344.Solution(); + System.out.println(test.solution(new int[][] {{5,5,5,5,5},{5,5,5,5,5},{5,5,5,5,5},{5,5,5,5,5}}, + new int[][] {{1,0,0,3,4,4},{1,2,0,2,3,2},{2,1,0,3,1,2},{1,0,1,3,3,1}})); + System.out.println(test.solution(new int[][] {{1,2,3},{4,5,6},{7,8,9}}, + new int[][] {{1,1,1,2,2,4},{1,0,0,1,1,2},{2,2,0,2,0,100}})); + } + + static class Solution { + public int solution(int[][] board, int[][] skill) { + int answer = 0; + int M = board.length+1; + int N = board[0].length+1; + int[][] map = new int[M][N]; + for (int[] info:skill) { + if (info[0] == 1) { + map[info[1]][info[2]] -= info[5]; + map[info[1]][info[4]+1] += info[5]; + map[info[3]+1][info[2]] += info[5]; + map[info[3]+1][info[4]+1] -= info[5]; + }else { + map[info[1]][info[2]] += info[5]; + map[info[1]][info[4]+1] -= info[5]; + map[info[3]+1][info[2]] -= info[5]; + map[info[3]+1][info[4]+1] += info[5]; + } + } + + for (int i = 0; i < M; i++) + for (int j = 1; j < N; j++) + map[i][j] += map[i][j-1]; + for (int i = 1; i < M; i++) + for (int j = 0; j < N; j++) + map[i][j] += map[i-1][j]; + for (int i = 0; i < M-1; i++) + for (int j = 0; j < N-1; j++) + if (board[i][j]+map[i][j] > 0) answer++; + return answer; + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ10026.java" "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ10026.java" new file mode 100644 index 0000000..caf88da --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ10026.java" @@ -0,0 +1,64 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ10026 { + /* 10026. 적록색약 + DFS + */ + static int[] dr = {-1, 0, 1, 0}; + static int[] dc = {0, 1, 0, -1}; + + public static boolean isValid(int n, int r, int c) { + return r >= 0 && r < n && c >= 0 && c < n; + } + + public static void dfs(char[][] map, char color, int n, int r, int c, boolean isNormal) { + map[r][c] = 0; + int nr, nc; + for (int i = 0; i < 4; i++) { + nr = r + dr[i]; + nc = c + dc[i]; + if (!isNormal && (color == 'R' || color == 'G')) { + if (isValid(n, nr, nc) && (map[nr][nc] == 'R' || map[nr][nc] == 'G')) + dfs(map, color, n, nr, nc, isNormal); + }else { + if (isValid(n, nr, nc) && map[nr][nc] == color) + dfs(map, color, n, nr, nc, isNormal); + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + char[][] map = new char[N][N]; + for (int i = 0; i < N; i++) map[i] = br.readLine().toCharArray(); + char[][] pMap = new char[N][N]; + char[][] qMap = new char[N][N]; + for (int i = 0; i < N; i++) { + pMap[i] = map[i].clone(); + qMap[i] = map[i].clone(); + } + int pResult = 0; + int qResult = 0; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if (pMap[i][j] != 0) { + dfs(pMap, pMap[i][j], N, i, j, true); + pResult++; + } + if (qMap[i][j] != 0) { + dfs(qMap, qMap[i][j], N, i, j, false); + qResult++; + } + } + } + + System.out.println(pResult+" "+qResult); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ1012.java" "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ1012.java" new file mode 100644 index 0000000..a4a4c0a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ1012.java" @@ -0,0 +1,62 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1012 { + /* 1012. 유기농 배추 + DFS + */ + static int[] dr = {-1, 0, 1, 0}; + static int[] dc = {0, 1, 0, -1}; + static int M, N, K, result; + static boolean[][] map; + + public static boolean isValid(int m, int n, int r, int c) { + return r >= 0 && r < m && c >= 0 && c < n; + } + + public static void dfs(int r, int c) { + map[r][c] = false; + int nr, nc; + for (int i = 0; i < 4; i++) { + nr = r + dr[i]; + nc = c + dc[i]; + if (isValid(M, N, nr, nc) && map[nr][nc]) + dfs(nr, nc); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int X, Y; + int T = Integer.parseInt(br.readLine()); + for (int i = 0; i < T; i++) { + result = 0; + st = new StringTokenizer(br.readLine()); + M = Integer.parseInt(st.nextToken()); + N = Integer.parseInt(st.nextToken()); + K = Integer.parseInt(st.nextToken()); + map = new boolean[M][N]; + for (int j = 0; j < K; j++) { + st = new StringTokenizer(br.readLine()); + X = Integer.parseInt(st.nextToken()); + Y = Integer.parseInt(st.nextToken()); + map[X][Y] = true; + } + for (int j = 0; j < M; j++) { + for (int k = 0; k < N; k++) { + if (map[j][k]) { + dfs(j, k); + result++; + } + } + } + System.out.println(result); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ14501.java" "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ14501.java" new file mode 100644 index 0000000..817bc33 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ14501.java" @@ -0,0 +1,30 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ14501 { + /* 14501. 퇴사 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int[] TP = new int[N+1]; + int T, P, result = 0; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + T = Integer.parseInt(st.nextToken()); + P = Integer.parseInt(st.nextToken()); + result = Math.max(TP[i], result); + if (i + T <= N) { + if (TP[i+T] < result + P) TP[i+T] = result + P; + } + } + result = Math.max(TP[N], result); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ2473.java" "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ2473.java" new file mode 100644 index 0000000..4cd75d3 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ2473.java" @@ -0,0 +1,42 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ2473 { + /* 2473. 세 용액 + 투 포인터 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + long[] arr = new long[N]; + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < N; i++) + arr[i] = Long.parseLong(st.nextToken()); + Arrays.sort(arr); + + int lef = 0, rig = N-1; + long first = 0, second = 0, third = 0, opt = Long.MAX_VALUE, sum; + + for (int i = 0; i < N-2; i++) { + lef = i + 1; rig = N - 1; + while (lef < rig) { + sum = arr[i] + arr[lef] + arr[rig]; + if (Math.abs(sum) < opt) { + opt = Math.abs(sum); + first = arr[i]; second = arr[lef]; third = arr[rig]; + } + + if (sum > 0) rig--; + else lef++; + } + } + + System.out.println(first+" "+second+" "+third); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ5567.java" "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ5567.java" new file mode 100644 index 0000000..0fbd437 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week27(220321)/BJ5567.java" @@ -0,0 +1,35 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.HashSet; +import java.util.StringTokenizer; + +public class BJ5567 { + /* 5567. 결혼식 + Set + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int n = Integer.parseInt(br.readLine()); + int m = Integer.parseInt(br.readLine()); + int a, b; + HashMap> friends = new HashMap<>(); + for (int i = 1; i <= n; i++) friends.put(i, new HashSet<>()); + for (int i = 0; i < m; i++) { + st = new StringTokenizer(br.readLine()); + a = Integer.parseInt(st.nextToken()); + b = Integer.parseInt(st.nextToken()); + friends.get(a).add(b); + friends.get(b).add(a); + } + + HashSet set = new HashSet<>(friends.get(1)); + for (int p: friends.get(1)) set.addAll(friends.get(p)); + set.remove(1); + System.out.println(set.size()); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ12912.java" "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ12912.java" new file mode 100644 index 0000000..15fbd1e --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ12912.java" @@ -0,0 +1,106 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class BJ12912 { + /* 12912. 트리 수정 + 트리의 지름, 임의의 x에서 가장 먼 노드 y => y에서 가장 먼 노드 z => y와 z사이의 거리가 지름 + */ + static int N, M; + static boolean[] visited; + static long dist, totalDist, result = 0; + static ArrayList> nodeList, temp; + static HashMap> map = new HashMap<>(); + + public static void findDiameter() { + HashMap nodes; + int to; long cost; + for (int from = 0; from < N; from++) { + nodes = nodeList.get(from); + for (Map.Entry entry:nodes.entrySet()) { + to = entry.getKey(); + cost = entry.getValue(); + if (map.get(from).contains(to)) continue; +// System.out.println(from+" "+to+" "+cost); + map.get(from).add(to); + map.get(to).add(from); + + temp.get(from).remove(to); + temp.get(to).remove(from); + totalDist = cost; + + M = from; + Arrays.fill(visited, false); + dist = 0; + findNode(from, 0); + Arrays.fill(visited, false); + dist = 0; + findNode(M, 0); + totalDist += dist; +// System.out.println("first:"+dist); + + M = to; + Arrays.fill(visited, false); + dist = 0; + findNode(to, 0); + Arrays.fill(visited, false); + dist = 0; + findNode(M, 0); +// System.out.println("second:"+dist); + totalDist += dist; +// System.out.println("total:"+totalDist); + + result = Math.max(result, totalDist); + temp.get(from).put(to,cost); + temp.get(to).put(from,cost); + } + } + } + + public static void findNode(int node, long cost) { + visited[node] = true; + if (cost > dist) { + M = node; + dist = cost; + } + int key; long val; + for (Map.Entry entry:temp.get(node).entrySet()) { + key = entry.getKey(); + val = entry.getValue(); +// System.out.println("node:"+node+", key:"+key+", val:"+val); + if (visited[key]) continue; + findNode(key,cost+val); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + N = Integer.parseInt(br.readLine()); + int from, to; + long cost; + visited = new boolean[N]; + for (int i = 0; i < N; i++) map.put(i, new HashSet<>()); + nodeList = new ArrayList<>(); + temp = new ArrayList<>(); + for (int i = 0; i < N; i++) { + nodeList.add(new HashMap<>()); + temp.add(new HashMap<>()); + } + for (int i = 0; i < N - 1; i++) { + st = new StringTokenizer(br.readLine()); + from = Integer.parseInt(st.nextToken()); + to = Integer.parseInt(st.nextToken()); + cost = Long.parseLong(st.nextToken()); + nodeList.get(from).put(to,cost); + nodeList.get(to).put(from,cost); + temp.get(from).put(to,cost); + temp.get(to).put(from,cost); + } + findDiameter(); + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ1890.java" "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ1890.java" new file mode 100644 index 0000000..cda278a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ1890.java" @@ -0,0 +1,53 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1890 { + /* 1890. 점프 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int[][] map = new int[N][N]; + long[][] DP = new long[N][N]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < N; j++) + map[i][j] = Integer.parseInt(st.nextToken()); + } + + DP[0][0] = 1; + map[N-1][N-1] = 1; + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if (DP[i][j] != 0 ) { + A:if (i + map[i][j] < N) { + for (int k = i + 1; k <= i + map[i][j]; k++) + if (map[k][j] == 0) break A; + DP[i + map[i][j]][j] += DP[i][j]; + } + B:if (j + map[i][j] < N) { + for (int k = j + 1; k <= j + map[i][j]; k++) + if (map[i][k] == 0) break B; + DP[i][j + map[i][j]] += DP[i][j]; + } + } +// System.out.println(i+" "+j); +// for (int k = 0; k < N; k++) { +// for (int l = 0; l < N; l++) { +// System.out.print(DP[k][l]+" "); +// } +// System.out.println(); +// } +// System.out.println(); + } + } + System.out.println(DP[N-1][N-1]); + } + +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ20500.java" "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ20500.java" new file mode 100644 index 0000000..ae2db1f --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week28(220328)/BJ20500.java" @@ -0,0 +1,29 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ20500 { + /* 20500. Ezreal 여눈부터 가네 ㅈㅈ + DP + */ + static int MOD = 1000000007; + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + long[][] DP = new long[N+1][3]; + DP[1][2] = 1; + for (int i = 2; i <= N; i++) { + for (int j = 0; j < 3; j++) { + if (DP[i-1][j] != 0) { + DP[i][(j+1)%3] = (DP[i][(j+1)%3] + DP[i-1][j]) % MOD; + DP[i][(j+5)%3] = (DP[i][(j+5)%3] + DP[i-1][j]) % MOD; + } + } + } + + System.out.println(DP[N][0]); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ16946.java" "b/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ16946.java" new file mode 100644 index 0000000..b1b484c --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ16946.java" @@ -0,0 +1,88 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.StringTokenizer; + +public class BJ16946 { + /* 16946. 벽 부수고 이동하기 4 + DFS + */ + private static int N, M, count; + private static final int[] dr = new int[] {-1, 0, 1, 0}; + private static final int[] dc = new int[] {0, 1, 0, -1}; + private static final ArrayList temp = new ArrayList<>(); + + public static boolean isValid(int r, int c) { + return r >= 0 && r < N && c >= 0 && c < M; + } + + public static void dfs(char[][] map, boolean[][] visited, int r, int c) { + visited[r][c] = true; + count++; + temp.add(new int[] {r, c}); + int nr, nc; + for (int i = 0; i < 4; i++) { + nr = r + dr[i]; nc = c + dc[i]; + if (isValid(nr, nc) && map[nr][nc] == '0' && !visited[nr][nc]) { + dfs(map, visited, nr, nc); + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + int[][] move = new int[N][M]; + int[][] label = new int[N][M]; + int K = 1; + char[][] map = new char[N][]; + for (int i = 0; i < N; i++) { + map[i] = br.readLine().toCharArray(); + } + boolean[][] visited = new boolean[N][M]; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + if (map[i][j] == '0' && !visited[i][j]) { + count = 0; + temp.clear(); + dfs(map, visited, i, j); + for (int[] rc:temp) { + move[rc[0]][rc[1]] = count; + label[rc[0]][rc[1]] = K; + } + K++; + } + } + } + + StringBuilder sb = new StringBuilder(); + int num, nr, nc; + HashSet set = new HashSet(); + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + if (map[i][j] == '0') sb.append('0'); + else { + num = 1; + set.clear(); + for (int k = 0; k < 4; k++) { + nr = i + dr[k]; nc = j + dc[k]; + if (isValid(nr, nc) && !set.contains(label[nr][nc])) { + set.add(label[nr][nc]); + num += move[nr][nc]; + } + } + sb.append(num % 10); + } + } + sb.append('\n'); + } + System.out.println(sb); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ4991.java" "b/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ4991.java" new file mode 100644 index 0000000..18f841a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week30(220411)/BJ4991.java" @@ -0,0 +1,100 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class BJ4991 { + /* 4991. 로봇 청소기 + BFS, TSP + */ + private final static int INF = 4001; + private static final int[] dr = new int[] {-1, 0, 1, 0}; + private static final int[] dc = new int[] {0, 1, 0, -1}; + private static final ArrayList arrayList = new ArrayList<>(); + private static int h, w; + + public static boolean isValid(int h, int w, int r, int c) { + return r >= 0 && r < h && c >= 0 && c < w; + } + + public static int bfs(char[][] map, int s, int e) { + int[] start = arrayList.get(s); + int[] end = arrayList.get(e); + int[][] visited = new int[h][w]; + visited[start[0]][start[1]] = 1; + Queue q = new LinkedList<>(); + q.offer(new int[] {start[0], start[1]}); + + int[] cur; + int nr, nc, cnt; + while(!q.isEmpty()) { + cur = q.poll(); + cnt = visited[cur[0]][cur[1]]; + for (int i = 0; i < 4; i++) { + nr = cur[0] + dr[i]; nc = cur[1] + dc[i]; + if (isValid(h, w, nr, nc) && map[nr][nc] != 'x' && visited[nr][nc] == 0) { + if (nr == end[0] && nc == end[1]) { + return cnt; + } + visited[nr][nc] = cnt + 1; + q.offer(new int[] {nr, nc}); + } + } + } + return -1; + } + + public static int TSP(int[][] W, int[][] DP, int N, int i, int V) { + if (V == (1 << N) - 1) { + if (W[i][0] == 0) return INF; + return 0; + } + if (DP[i][V] < INF) return DP[i][V]; + for (int j = 0; j < N; j++) + if (((1 << j) & V) == 0 && W[i][j] != 0) + DP[i][V] = Math.min(DP[i][V], W[i][j] + TSP(W, DP, N, j, V | (1 << j))); + return DP[i][V]; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + outer:while(true) { + st = new StringTokenizer(br.readLine()); + w = Integer.parseInt(st.nextToken()); + h = Integer.parseInt(st.nextToken()); + if (w == 0 && h == 0) break; + char[][] map = new char[h][]; + for (int i = 0; i < h; i++) map[i] = br.readLine().toCharArray(); + arrayList.clear(); + + for (int i = 0; i < h; i++) { + for (int j = 0; j < w; j++) { + if (map[i][j] == '*') arrayList.add(new int[] {i, j}); + else if (map[i][j] == 'o') + arrayList.add(0, new int[] {i, j}); + } + } + + int N = arrayList.size(); + int[][] W = new int[N][N]; + int[][] DP = new int[N][(1 << N) - 1]; + + for (int i = 0; i < N; i++) { + for (int j = i + 1; j < N; j++) { + W[i][j] = bfs(map, i, j); + W[j][i] = W[i][j]; + if (W[i][j] < 0) { + System.out.println(-1); + continue outer; + } + } + } + + for (int i = 0; i < N; i++) Arrays.fill(DP[i], INF); + System.out.println(TSP(W, DP, N, 0, 1)); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ1007.java" "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ1007.java" new file mode 100644 index 0000000..1faf145 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ1007.java" @@ -0,0 +1,66 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1007 { + /* 1007. 벡터 매칭 + 조합 + */ + private static double result = Double.MAX_VALUE; + private static Point[] points; + private static int M, N; + public static class Point { + int x, y; + public Point(int x, int y) { + this.x = x; + this.y = y; + } + } + + public static double calculate(int[] arr) { + int vecX = 0, vecY = 0; + for (int i = 0; i < N; i++) { + vecX += points[i].x; + vecY += points[i].y; + } + for (int i = 0; i < M; i++) { + vecX -= 2 * points[arr[i]].x; + vecY -= 2 * points[arr[i]].y; + } + return Math.sqrt((double) vecX * vecX + (double) vecY * vecY); + } + + private static void combination(int[] arr, int n, int r, int cnt, int s) { + if (cnt == r) { + result = Math.min(result, calculate(arr)); + return; + } + for (int i = s; i < n; i++) { + arr[cnt] = i; + combination(arr, n, r, cnt + 1, i + 1); + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int T = Integer.parseInt(br.readLine()); + for (int i = 0; i < T; i++) { + result = Double.MAX_VALUE; + N = Integer.parseInt(br.readLine()); + points = new Point[N]; + for (int j = 0; j < N; j++) { + st = new StringTokenizer(br.readLine()); + points[j] = new Point(Integer.parseInt(st.nextToken()), + Integer.parseInt(st.nextToken())); + } + M = N / 2; + int[] arr = new int[M]; + combination(arr, N, M, 0, 0); + System.out.println(result); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ11049.java" "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ11049.java" new file mode 100644 index 0000000..25b8c9a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ11049.java" @@ -0,0 +1,39 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ11049 { + /* 11049. 행렬 곱셈 순서 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int[][] dims = new int[N][2]; + int[][] DP = new int[N][N]; + for (int i = 0; i < N; i++) Arrays.fill(DP[i], Integer.MAX_VALUE); + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + dims[i][0] = Integer.parseInt(st.nextToken()); + dims[i][1] = Integer.parseInt(st.nextToken()); + DP[i][i] = 0; + } + + for (int i = 0; i < N-1; i++) DP[i][i+1] = dims[i][0] * dims[i][1] * dims[i+1][1]; + + for (int i = N-3; i >= 0; i--) { + for (int j = i + 2; j < N; j++) { + for (int k = i; k < j; k++) { + DP[i][j] = Math.min(DP[i][j], DP[i][k] + DP[k+1][j] + dims[i][0] * dims[k][1] * dims[j][1]); + } + } + } + + System.out.println(DP[0][N-1]); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ14888.java" "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ14888.java" new file mode 100644 index 0000000..70ee4dd --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ14888.java" @@ -0,0 +1,48 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ14888 { + /* 14888. 연산자 끼워넣기 + DFS + */ + private static int N, maxRes = Integer.MIN_VALUE, minRes = Integer.MAX_VALUE; + private static final int[] op = new int[4]; + + public static void dfs(int[] arr, int cnt, int res) { + if (cnt == N-1) { + maxRes = Math.max(maxRes, res); + minRes = Math.min(minRes, res); + return; + } + + for (int i = 0; i < 4; i++) { + if (op[i] > 0) { + op[i]--; + if (i == 0) dfs(arr, cnt + 1, res + arr[cnt + 1]); + else if (i == 1) dfs(arr, cnt + 1, res - arr[cnt + 1]); + else if (i == 2) dfs(arr, cnt + 1, res * arr[cnt + 1]); + else dfs(arr, cnt + 1, res / arr[cnt + 1]); + op[i]++; + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + N = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + int[] arr = new int[N]; + for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < 4; i++) op[i] = Integer.parseInt(st.nextToken()); + + dfs(arr, 0, arr[0]); + System.out.println(maxRes); + System.out.println(minRes); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ15685.java" "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ15685.java" new file mode 100644 index 0000000..ad8173b --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ15685.java" @@ -0,0 +1,71 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BJ15685 { + /* 15685. 드래곤 커브 + 시뮬레이션 + */ + private static final int MAX_SIZE = 101; + private static final int[] dr = new int[] {0, -1, 0, 1}; + private static final int[] dc = new int[] {1, 0, -1, 0}; + + public static class Curve { + int x, y, d, g; + public Curve(int y, int x, int d, int g) { + this.x = x; + this.y = y; + this.d = d; + this.g = g; + } + } + + public static void generateCurve(boolean[][] map, Curve curve) { + ArrayList arrayList = new ArrayList<>(); + int nx = curve.x, ny = curve.y; + int[] orig, cur; + map[nx][ny] = true; + arrayList.add(new int[] {nx, ny}); + nx += dr[curve.d]; + ny += dc[curve.d]; + map[nx][ny] = true; + arrayList.add(new int[] {nx, ny}); + + int len, dx, dy; + for (int i = 0; i < curve.g; i++) { + len = arrayList.size(); + orig = arrayList.get(len - 1); + for (int j = len - 2; j >= 0; j--) { + cur = arrayList.get(j); + nx = orig[0] + (cur[1] - orig[1]); + ny = orig[1] + (orig[0] - cur[0]); + map[nx][ny] = true; + arrayList.add(new int[] {nx, ny}); + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + boolean[][] map = new boolean[MAX_SIZE][MAX_SIZE]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + generateCurve(map, new Curve(Integer.parseInt(st.nextToken()), + Integer.parseInt(st.nextToken()), + Integer.parseInt(st.nextToken()), + Integer.parseInt(st.nextToken()))); + } + + int result = 0; + for (int i = 0; i < MAX_SIZE-1; i++) + for (int j = 0; j < MAX_SIZE-1; j++) + if (map[i][j] && map[i+1][j] && map[i][j+1] && map[i+1][j+1]) result++; + System.out.println(result); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ2580.java" "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ2580.java" new file mode 100644 index 0000000..b787ecd --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week31(220418)/BJ2580.java" @@ -0,0 +1,74 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.StringTokenizer; + +public class BJ2580 { + /* 2580. 스도쿠 + 완전탐색 + */ + private static final int MAX_NUM = 9; + private static final boolean[][] rowCheck = new boolean[MAX_NUM][MAX_NUM+1]; + private static final boolean[][] colCheck = new boolean[MAX_NUM][MAX_NUM+1]; + private static final boolean[][] squareCheck = new boolean[MAX_NUM][MAX_NUM+1]; + private static final ArrayList arrayList = new ArrayList<>(); + + private static void dfs(int[][] map, int cnt) { + if (cnt == arrayList.size()) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < MAX_NUM; i++) { + for (int j = 0; j < MAX_NUM; j++) { + sb.append(map[i][j]).append(" "); + } + sb.append("\n"); + } + System.out.println(sb); + System.exit(0); + } + int r = arrayList.get(cnt)[0]; + int c = arrayList.get(cnt)[1]; + for (int i = 1; i <= MAX_NUM; i++) { + if (rowCheck[r][i] || colCheck[c][i] || squareCheck[(r/3)*3+(c/3)][i]) continue; + rowCheck[r][i] = true; + colCheck[c][i] = true; + squareCheck[(r/3)*3+(c/3)][i] = true; + map[r][c] = i; + dfs(map, cnt + 1); + rowCheck[r][i] = false; + colCheck[c][i] = false; + squareCheck[(r/3)*3+(c/3)][i] = false; + map[r][c] = 0; + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int[][] map = new int[MAX_NUM][MAX_NUM]; + for (int i = 0; i < MAX_NUM; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < MAX_NUM; j++) { + map[i][j] = Integer.parseInt(st.nextToken()); + } + } + for (int i = 0; i < MAX_NUM; i++) { + for (int j = 0; j < MAX_NUM; j++) { + if (map[i][j] != 0) { + rowCheck[i][map[i][j]] = true; + colCheck[j][map[i][j]] = true; + }else arrayList.add(new int[] {i, j}); + } + } + int r, c; + for (int i = 0; i < MAX_NUM; i++) { + r = (i / 3) * 3; c = (i % 3) * 3; + for (int j = r; j < r+3; j++) + for (int k = c; k < c+3; k++) + squareCheck[i][map[j][k]] = true; + } + dfs(map, 0); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ10942.java" "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ10942.java" new file mode 100644 index 0000000..dbb7907 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ10942.java" @@ -0,0 +1,43 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ10942 { + /* 10942. 팰린드롬? + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + boolean[][] dp = new boolean[N][N]; + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(st.nextToken()); + dp[i][i] = true; + } + for (int i = 0; i < N-1; i++) + if (arr[i] == arr[i+1]) dp[i][i+1] = true; + for (int i = 2; i < N; i++) + for (int j = 0; j < N-i; j++) + if (dp[j+1][j+i-1] && arr[j] == arr[j+i]) dp[j][j+i] = true; + + int s, e; + int M = Integer.parseInt(br.readLine()); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + s = Integer.parseInt(st.nextToken()); + e = Integer.parseInt(st.nextToken()); + if (dp[s-1][e-1]) sb.append(1); + else sb.append(0); + sb.append("\n"); + } + System.out.println(sb); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ2234.java" "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ2234.java" new file mode 100644 index 0000000..c3f8846 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ2234.java" @@ -0,0 +1,85 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.StringTokenizer; + +public class BJ2234 { + /* 2234. 성곽 + DFS + */ + private static final int[] dr = {0, -1, 0, 1}; + private static final int[] dc = {-1, 0, 1, 0}; + private static int cnt; + + public static boolean isValid(int r, int c, int m, int n) { + return r >= 0 && r < m && c >= 0 && c < n; + } + + public static void dfs(int r, int c, boolean[][][] map, int[][] visited, int idx) { + visited[r][c] = idx; + cnt++; + int nr, nc; + for (int i = 0; i < 4; i++) { + if (map[r][c][i]) { + nr = r + dr[i]; nc = c + dc[i]; + if (visited[nr][nc] == 0) dfs(nr, nc, map, visited, idx); + } + } + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + boolean[][][] map = new boolean[M][N][4]; + int[][] visited = new int[M][N]; + int temp, p; + for (int i = 0; i < M; i++) { + st = new StringTokenizer(br.readLine()); + for (int j = 0; j < N; j++) { + temp = Integer.parseInt(st.nextToken()); + p = 8; + for (int k = 0; k < 4; k++) { + if (temp >= p) temp -= p; + else map[i][j][3-k] = true; + p /= 2; + } + } + } + + int idx = 0; + int maxSize = 0; + HashMap sizeMap = new HashMap<>(); + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + if (visited[i][j] == 0) { + cnt = 0; + dfs(i, j, map, visited, ++idx); + maxSize = Math.max(maxSize, cnt); + sizeMap.put(idx, cnt); + } + } + } + + int maxSumSize = 0; + int nr, nc; + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + for (int k = 0; k < 4; k++) { + if (!map[i][j][k]) { + nr = i + dr[k]; nc = j + dc[k]; + if (isValid(nr, nc, M, N) && visited[i][j] != visited[nr][nc]) + maxSumSize = Math.max(maxSumSize, sizeMap.get(visited[i][j]) + sizeMap.get(visited[nr][nc])); + } + } + } + } + System.out.println(idx); + System.out.println(maxSize); + System.out.println(maxSumSize); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ9207.java" "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ9207.java" new file mode 100644 index 0000000..59685e2 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week34(220523)/BJ9207.java" @@ -0,0 +1,75 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +public class BJ9207 { + /* 9207. 페크 솔리테어 + DFS + */ + private static final int MAX_ROW = 5; + private static final int MAX_COL = 9; + private static final int MAX_NUM = 8; + private static final int[] dr = {-1, 0, 1, 0}; + private static final int[] dc = {0, 1, 0, -1}; + private static int minPin, minMove; + + public static boolean isValid(int r, int c) { + return r >= 0 && r < MAX_ROW && c >= 0 && c < MAX_COL; + } + public static void dfs(char[][] map, HashSet set, int cnt) { + int r, c, br, bc, nr, nc; + List list = new ArrayList<>(set); + for (int s:list) { + r = s / MAX_COL; + c = s % MAX_COL; + for (int i = 0; i < 4; i++) { + br = r + dr[i]; bc = c + dc[i]; + nr = r + 2 * dr[i]; nc = c + 2 * dc[i]; + if (isValid(nr, nc) && map[nr][nc] == '.' && map[br][bc] == 'o') { + map[r][c] = '.'; map[br][bc] = '.'; map[nr][nc] = 'o'; + set.remove(r * MAX_COL + c); + set.remove(br * MAX_COL + bc); + set.add(nr * MAX_COL + nc); + dfs(map, set, cnt+1); + map[r][c] = 'o'; map[br][bc] = 'o'; map[nr][nc] = '.'; + set.remove(nr * MAX_COL + nc); + set.add(br * MAX_COL + bc); + set.add(r * MAX_COL + c); + } + } + } + int pin = 0; + for (int j = 0; j < MAX_ROW; j++) + for (int k = 0; k < MAX_COL; k++) + if (map[j][k] == 'o') pin++; + + if (pin < minPin) { + minPin = pin; + minMove = cnt; + }else if (pin == minPin && cnt < minMove) minMove = cnt; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + char[][] map = new char[MAX_ROW][MAX_COL]; + HashSet set = new HashSet<>(); + for (int i = 0; i < N; i++) { + set.clear(); + for (int j = 0; j < MAX_ROW; j++) map[j] = br.readLine().toCharArray(); + for (int j = 0; j < MAX_ROW; j++) + for (int k = 0; k < MAX_COL; k++) + if (map[j][k] == 'o') set.add(j * MAX_COL + k); + minPin = MAX_NUM; + minMove = Integer.MAX_VALUE; + dfs(map, set, 0); + br.readLine(); + System.out.println(minPin + " " + minMove); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1655.java" "b/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1655.java" new file mode 100644 index 0000000..f40b87a --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1655.java" @@ -0,0 +1,52 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Comparator; +import java.util.PriorityQueue; + +public class BJ1655 { + /* 1655. 가운데를 말해요 + 우선순위 큐(더위사냥, 쌍쌍바) + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + PriorityQueue lef = new PriorityQueue<>(Comparator.comparing(Integer::intValue).reversed()); + PriorityQueue rig = new PriorityQueue<>(); + StringBuilder sb = new StringBuilder(); + int first, second; + if (N == 1) sb.append(br.readLine()).append('\n'); + else { + first = Integer.parseInt(br.readLine()); + second = Integer.parseInt(br.readLine()); + if (first < second) { + lef.add(first); + rig.add(second); + }else { + lef.add(second); + rig.add(first); + } + sb.append(Integer.toString(first) + '\n' + lef.peek().toString() + '\n'); + for (int i = 2; i < N; i++) { + first = Integer.parseInt(br.readLine()); + if (first < rig.peek()) { + if (lef.size() <= rig.size()) lef.add(first); + else if (first < lef.peek()) { + rig.add(lef.poll()); + lef.add(first); + }else rig.add(first); + }else { + if (lef.size() > rig.size()) rig.add(first); + else { + lef.add(rig.poll()); + rig.add(first); + } + } + sb.append(lef.peek().toString() + '\n'); + } + } + System.out.println(sb); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1912.java" "b/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1912.java" new file mode 100644 index 0000000..c79e253 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week35(220530)/BJ1912.java" @@ -0,0 +1,23 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ1912 { + /* 1912. 연속합 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + StringTokenizer st = new StringTokenizer(br.readLine()); + int[] dp = new int[N]; + int ans = -1000; + for (int i = 0; i < N; i++) dp[i] = Integer.parseInt(st.nextToken()); + for (int i = 1; i < N; i++) dp[i] = Math.max(dp[i], dp[i] + dp[i-1]); + for (int i = 0; i < N; i++) ans = Math.max(ans, dp[i]); + System.out.println(ans); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ12026.java" "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ12026.java" new file mode 100644 index 0000000..03f45ca --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ12026.java" @@ -0,0 +1,56 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.StringTokenizer; + +public class BJ12026 { + /* 12026. BOJ 거리 + 완전탐색 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + ArrayList B = new ArrayList<>(); + ArrayList O = new ArrayList<>(); + ArrayList J = new ArrayList<>(); + int[] arr = new int[N]; + Arrays.fill(arr, -1); + arr[0] = 0; + B.add(0); + char[] boj = br.readLine().toCharArray(); + int temp; + for (int i = 1; i < N; i++) { + temp = Integer.MAX_VALUE; + if (boj[i] == 'B') { + for (int j:J) { + temp = Math.min(temp, arr[j] + (i - j) * (i - j)); + } + if (temp != Integer.MAX_VALUE) { + arr[i] = temp; + B.add(i); + } + } else if (boj[i] == 'O') { + for (int b:B) { + temp = Math.min(temp, arr[b] + (i - b) * (i - b)); + } + if (temp != Integer.MAX_VALUE) { + arr[i] = temp; + O.add(i); + } + } else if (boj[i] == 'J') { + for (int o:O) { + temp = Math.min(temp, arr[o] + (i - o) * (i - o)); + } + if (temp != Integer.MAX_VALUE) { + arr[i] = temp; + J.add(i); + } + } + } + System.out.println(arr[N-1]); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ1946.java" "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ1946.java" new file mode 100644 index 0000000..2bd5369 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ1946.java" @@ -0,0 +1,38 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.StringTokenizer; + +public class BJ1946 { + /* 1946. 신입사원 + 정렬 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + int T = Integer.parseInt(br.readLine()); + + for (int i = 0; i < T; i++) { + int N = Integer.parseInt(br.readLine()); + ArrayList list = new ArrayList<>(); + for (int j = 0; j < N; j++) { + st = new StringTokenizer(br.readLine()); + list.add(new int[] { + Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()) + }); + } + list.sort(Comparator.comparing(ints -> ints[0])); + + int temp = N; + for (int[] e:list) { + if (e[1] > temp) N--; + temp = Math.min(temp, e[1]); + } + System.out.println(N); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ5430.java" "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ5430.java" new file mode 100644 index 0000000..b2d1fe0 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week36(220613)/BJ5430.java" @@ -0,0 +1,52 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.*; + +public class BJ5430 { + /* 5430. AC + 덱 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int T = Integer.parseInt(br.readLine()); + + for (int i = 0; i < T; i++) { + boolean isFoward = true; + char[] func = br.readLine().toCharArray(); + int n = Integer.parseInt(br.readLine()); + String arr = br.readLine(); + String[] nums = arr.substring(1, arr.length() - 1).split(","); + Deque deque; + if (nums.length >= 1 && "".equals(nums[0])) deque = new ArrayDeque<>(); + else deque = new ArrayDeque<>(Arrays.asList(nums)); + StringBuilder result = new StringBuilder(); + for (char f:func) { + if (f == 'R') { + if (isFoward) isFoward = false; + else isFoward = true; + } else if (f == 'D') { + if (!deque.isEmpty()) { + if (isFoward) deque.pollFirst(); + else deque.pollLast(); + } else { + result = new StringBuilder("error"); + break; + } + } + } + + List list = new ArrayList<>(deque); + if (!"error".equals(result.toString())) { + result.append("["); + if (!isFoward) Collections.reverse(list); + for (String str:list) result.append(str).append(","); + if (!list.isEmpty()) result.deleteCharAt(result.length() - 1); + result.append("]"); + } + System.out.println(result); + } + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ18870.java" "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ18870.java" new file mode 100644 index 0000000..4900bc2 --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ18870.java" @@ -0,0 +1,39 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.HashMap; +import java.util.StringTokenizer; + +public class BJ18870 { + /* 18870. 좌표 압축 + 정렬 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + StringTokenizer st = new StringTokenizer(br.readLine()); + int[] arr = new int[N]; + int[] sorted = new int[N]; + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(st.nextToken()); + sorted[i] = arr[i]; + } + Arrays.sort(sorted); + int p = sorted[0]; + int q = 0; + HashMap map = new HashMap<>(); + map.put(p,q); + for (int i = 1; i < N; i++) { + if (sorted[i] == p) continue; + map.put(sorted[i], ++q); + p = sorted[i]; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < N; i++) sb.append(map.get(arr[i])).append(" "); + System.out.println(sb); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2631.java" "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2631.java" new file mode 100644 index 0000000..dd679df --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2631.java" @@ -0,0 +1,30 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class BJ2631 { + /* 2631. 줄세우기 + DP + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + int[] DP = new int[N]; + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(br.readLine()); + DP[i] = 1; + } + for (int i = 1; i < N; i++) { + for (int j = 0; j < i; j++) { + if (arr[j] <= arr[i] && DP[j] + 1 > DP[i]) DP[i] = DP[j] + 1; + } + } + + int maxVal = 0; + for (int i = 0; i < N; i++) maxVal = Math.max(maxVal, DP[i]); + System.out.println(N - maxVal); + } +} diff --git "a/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2805.java" "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2805.java" new file mode 100644 index 0000000..2c7a68b --- /dev/null +++ "b/src/\352\271\200\353\217\204\355\230\204/week37(220620)/BJ2805.java" @@ -0,0 +1,39 @@ +package bj; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class BJ2805 { + /* 2805. 나무 자르기 + 이분탐색 + */ + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + int N = Integer.parseInt(st.nextToken()); + long M = Long.parseLong(st.nextToken()); + int[] arr = new int[N]; + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); + + int lef = 0; + int rig = Integer.MAX_VALUE; + int mid; + long sum = 0; + int answer = 0; + while(lef <= rig) { + mid = (lef + rig) / 2; + sum = 0; + for (int i = 0; i < N; i++) sum += Math.max(0, arr[i] - mid); + if (sum >= M) { + lef = mid + 1; + answer = mid; + }else { + rig = mid - 1; + } + } + System.out.println(answer); + } +} diff --git "a/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_1007/Main.java" "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_1007/Main.java" new file mode 100644 index 0000000..dcdfd3b --- /dev/null +++ "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_1007/Main.java" @@ -0,0 +1,71 @@ +package BOJ_1007; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + + +public class Main { + static int n; + static int[][] point; + static boolean[] inCombination; + static double answer; + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static StringTokenizer st = null; + //TODO: 입력 받고 조합별로 계산해서 값 처리 + public static void main(String[] args) throws IOException { + int testCase = Integer.parseInt(br.readLine()); + for(int t = 0;tb ? b : a; + } + + private static double curValue() { + int x = 0, y = 0; + for(int i = 0;icandidateValue ? candidateValue : i; + } +} diff --git "a/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_14888/Main.java" "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_14888/Main.java" new file mode 100644 index 0000000..bb77501 --- /dev/null +++ "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_14888/Main.java" @@ -0,0 +1,73 @@ +package BOJ_14888; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +public class Main { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static StringTokenizer st = null; + static long max = Long.MIN_VALUE, min = Long.MAX_VALUE; + static int n = 0; + static int[] num; + static int[] operand = new int[4]; + + public static void main(String[] args) throws IOException { + input(); + solve(0,num[0]); + System.out.println(max); + System.out.println(min); + } + + private static void input() throws IOException { + n = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + num = new int[n]; + for(int i = 0;i0){ + operand[0]--; + solve(depth+1,value+num[depth+1]); + operand[0]++; + } + if(operand[1]>0){ + operand[1]--; + solve(depth+1,value-num[depth+1]); + operand[1]++; + } + if(operand[2]>0){ + operand[2]--; + solve(depth+1,value*num[depth+1]); + operand[2]++; + } + if(operand[3]>0){ + operand[3]--; + solve(depth+1,value/num[depth+1]); + operand[3]++; + } + } + + private static long getMax(long max, int value) { + return max < value ? value : max; + } + + private static long getMin(long min, int value) { + return min > value ? value : min; + } + + +} diff --git "a/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_15685/Main.java" "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_15685/Main.java" new file mode 100644 index 0000000..d67d8b3 --- /dev/null +++ "b/src/\354\213\240\355\231\215\354\262\240/week31/BOJ_15685/Main.java" @@ -0,0 +1,65 @@ +package BOJ_15685; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +public class Main { + static final int MAX_R = 100,MAX_C = 100; + static int[][] memField = new int[MAX_R+1][MAX_C+1]; + static int[] dx = {1,0,-1,0}; + static int[] dy = {0,-1,0,1}; + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = null; + int n = Integer.parseInt(br.readLine()); + for(int i = 0;i direction = new ArrayList<>(); + direction.add(dir); + + for(int i = 1;i<=generation;i++){ + for(int j = direction.size()-1;j>=0;j--){ + direction.add((direction.get(j)+1)%4); + } + } + memField[startY][startX] = 1; + for(Integer i: direction){ + startX += dx[i]; + startY += dy[i]; + memField[startY][startX] = 1; + } + } + + private static int answerCheck() { + int cnt = 0; + for(int i = 0;i{ + int no; + int seq; + + public DotInfo(int no, int seq) { + this.no = no; + this.seq = seq; + } + + @Override + public int compareTo(DotInfo o) { + return this.no > o.no ? 1 : -1; + } + } + public static void main(String[] args) throws IOException { + int n = Integer.parseInt(br.readLine()); + PriorityQueue pq = new PriorityQueue<>(); + DotInfo input; + int num = 0, pre = Integer.MIN_VALUE; + int[] answer = new int[n]; + + st = new StringTokenizer(br.readLine()); + for(int i = 0;i arr[j] && dp[i]mid) tree+= arr[i]-mid; + } + if(tree>=m) { + left = mid+1; + }else if(tree pq 사용해서 O(NlogN)으로 만들기 + * + * + * 시간복잡도: + * O(NlogN) + * + * + * 풀이에 걸린 시간: + */ + + static class Node implements Comparable{ + int no, time; + + public Node(int no, int time) { + super(); + this.no = no; + this.time = time; + } + + @Override + public int compareTo(Node o) { + return this.time-o.time; + } + + } + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int tc = Integer.parseInt(in.readLine()); + StringTokenizer st; + for (int T = 1; T <= tc; T++) { + + st = new StringTokenizer(in.readLine()); + + int n = Integer.parseInt(st.nextToken()); + int d = Integer.parseInt(st.nextToken()); + int c = Integer.parseInt(st.nextToken()); + + ArrayList[] adjList = new ArrayList[n+1]; + + for (int i = 0; i < adjList.length; i++) { + adjList[i] = new ArrayList(); + } + + for (int i = 0; i < d; i++) { + st = new StringTokenizer(in.readLine()); + + int a = Integer.parseInt(st.nextToken()); + int b = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + + adjList[b].add(new Node(a,s)); + } + + + int[] dist = new int[n+1]; + Arrays.fill(dist, Integer.MAX_VALUE); + boolean[] visited = new boolean[n+1]; + + PriorityQueue pq = new PriorityQueue<>(); + + pq.offer(new Node(c,0)); + dist[c] = 0; + + while(!pq.isEmpty()) { + + // 아직 감염되지 않은 지점 중 가장 빨리 감염되는 곳 선정 + Node current = pq.poll(); + if(visited[current.no]) continue; // 이미 방문한 지역인 경우 무시 + + visited[current.no] = true; // 방문 처리 + + + // 아직 감염되지 않은 컴퓨터들 중 새롭게 감염된 컴퓨터로부터 감염될 수 있는 컴퓨터들의 감염되는 시간배열 갱신 + for (int i = 0; i < adjList[current.no].size(); i++) { + Node adjNode = adjList[current.no].get(i); + if(!visited[adjNode.no] && dist[adjNode.no] > dist[current.no] + adjNode.time) { + dist[adjNode.no] = dist[current.no] + adjNode.time; + pq.offer(new Node(adjNode.no, dist[adjNode.no])); + } + } + } + + + // 방문한 컴퓨터 개수와 최장시간 구하기 + int max = 0; + int cnt = 0; + for (int i = 0; i < dist.length; i++) { + if(visited[i]) { + cnt++; + if(max=0) { // 0이 존재하면 + + // 0, 가장 작은 양수 조합 + if(zeroIdx0 && bestResult>-arr[zeroIdx-1]) { + bestResult = -arr[zeroIdx-1]; + answer[0] = arr[zeroIdx-1]; + answer[1] = 0; + } + + // 음수, 양수 조합 중 최적의 조합 찾기 + if(zeroIdx0) + findBestCase(zeroIdx-1, zeroIdx+1); + + }else { // 0이 없으면 + int startOfPositive = -zeroIdx -1; + int startOfNegative = -zeroIdx -2; + + // 가장 큰 두 음수 조합 + if(startOfNegative>0) { + bestResult = Math.abs(arr[startOfNegative] + arr[startOfNegative-1]); + answer[0] = arr[startOfNegative-1]; + answer[1] = arr[startOfNegative]; + } + // 가장 작은 두 양수 조합 + if(startOfPositive arr[startOfPositive] + arr[startOfPositive+1]) { + bestResult = arr[startOfPositive] + arr[startOfPositive+1]; + answer[0] = arr[startOfPositive]; + answer[1] = arr[startOfPositive+1]; + } + + // 음수, 양수 조합 중 최적의 조합 찾기 + if(startOfNegative>=0 && startOfPositive=0 && jMath.abs(result)) { + bestResult = Math.abs(result); + answer[0] = arr[i]; + answer[1] = arr[j]; + } + if(i>0 && result>0) { + i--; + }else if(j=0 && newRow=0 && newCol stack = new Stack<>(); +// ArrayList table = new ArrayList<>(); +// int pointer = k; +// +// for (int i = 0; i < n; i++) { +// table.add(i); +// } +// +// for (String command : cmd) { +// String[] split = command.split(" "); +// if(split[0].equals("U")) { +// pointer -= Integer.parseInt(split[1]); +// +// } +// else if(split[0].equals("D")) { +// pointer += Integer.parseInt(split[1]); +// } +// else if(split[0].equals("C")) { +// stack.push(new int[] {pointer, table.get(pointer)}); +// deleted[table.get(pointer)] = true; +// table.remove(pointer); +// if(pointer==table.size()) pointer--; +// } +// else if(split[0].equals("Z")) { +// int[] history = stack.pop(); +// int idx = history[0]; +// int num = history[1]; +// deleted[num] = false; +// table.add(idx, num); +// if(idx<=pointer) pointer ++; +// } +// +// } +// +// StringBuilder sb = new StringBuilder(); +// for (int i = 0; i < deleted.length; i++) { +// if(deleted[i]) sb.append("X"); +// else sb.append("O"); +// } +// +// return sb.toString(); +// } + + static public String solution(int n, int k, String[] cmd) { + + Stack stack = new Stack<>(); + int pointer = k; + int size = n; + + for (String command : cmd) { + String[] split = command.split(" "); + + if(split[0].equals("U")) { // 위로 이동 + pointer -= Integer.parseInt(split[1]); + + } + else if(split[0].equals("D")) { // 아래로 이동 + pointer += Integer.parseInt(split[1]); + } + else if(split[0].equals("C")) { // 삭제 + stack.push(pointer); + size--; + if(pointer==size) pointer--; + } + else if(split[0].equals("Z")) { // 복구 + int history = stack.pop(); + size++; + if(history<=pointer) pointer ++; + } + + } + + // 결과 문자열 생성 + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < size; i++) { + sb.append("O"); + } + + while(!stack.isEmpty()) { + int idx = stack.pop(); + sb.insert(idx, "X"); + } + + return sb.toString(); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1005_ACMCraft.java" "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1005_ACMCraft.java" new file mode 100644 index 0000000..604a542 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1005_ACMCraft.java" @@ -0,0 +1,104 @@ +package com.ssafy.algo.study.week18; + +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.Scanner; + +/** + * 문제:ACM Craft 링크:https://www.acmicpc.net/problem/1005 + * + * 접근: 위상정렬 문제입니다. + * 1. 각 건물을 짓기 위해 필요한 건물의 수를 나타내는 차수 배열 생성 + * 2. 차수가 0인 건물들 부터 우선순위 큐에 삽입 + * 3. 큐에서 건물들을 순서대로 빼면서 빼낸 건물 다음에 지어져야할 건물의 차수 하나씩 감소시키기 + * 4. 아직 지어지지 않은 건물 중에서 차수가 0인 건물을 큐에 삽입 + * + * 시간복잡도: + * O(N^2) + * + * 소요 시간: + * 1h + * + */ +public class BJ_1005_ACMCraft { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int T = sc.nextInt(); // 테스트 케이스 수 + + for (int tc = 1; tc <= T; tc++) { + + int N = sc.nextInt(); // 건물의 개수 + int K = sc.nextInt(); // 건설 순서 규칙 총 개수 + int[] D = new int[N+1]; // 건물당 건설에 걸리는 시간 + boolean[] done = new boolean[N+1]; // 건설 완료 여부 + + for (int i = 1; i <= N; i++) { + D[i] = sc.nextInt(); + } + + boolean[][] adjMatrix = new boolean[N+1][N+1]; // 인접행렬로 나타낸 건물들의 선행 관계 + int[] degrees = new int[N+1]; // 건물의 차수(건물을 짓기 위해 먼저 지어져야하는 건물의 수) + + for (int j = 0; j < K; j++) { + int X = sc.nextInt(); + int Y = sc.nextInt(); + + adjMatrix[X][Y] = true; + + degrees[Y]++; + } + + int W = sc.nextInt(); + + // 우선 순위 큐(건설 완료 시간으로 오름차순 정렬) + PriorityQueue q = new PriorityQueue<>(new Comparator(){ + + @Override + public int compare(int[] o1, int[] o2) { + return o1[1] - o2[1]; + } + + }); + + // 차수가 0인 건물들부터 큐에 삽입 + for (int i = 1; i < degrees.length; i++) { + if(degrees[i]==0) { + q.add(new int[] {i, D[i]}); + done[i] = true; + } + + } + + while(!q.isEmpty()) { + int[] data = q.poll(); + int building = data[0]; // 지어진 건물 번호 + int time = data[1]; // 건물이 건설 완료된 시간 + + // W면 종료 + if(building==W) { + System.out.println(time); + break; + } + + // 차수 줄이기 + for (int i = 1; i < adjMatrix.length; i++) { + if(adjMatrix[building][i]) + degrees[i]--; + } + + // 차수가 0이된 건물 큐에 삽입 + for (int i = 1; i < degrees.length; i++) { + if(degrees[i]==0 && !done[i]) { + q.add(new int[] {i, time + D[i]}); + done[i] = true; + } + } + } + + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1238_\355\214\214\355\213\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1238_\355\214\214\355\213\260.java" new file mode 100644 index 0000000..ddc0455 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_1238_\355\214\214\355\213\260.java" @@ -0,0 +1,67 @@ +package com.ssafy.algo.study.week18; + +import java.util.Arrays; +import java.util.Scanner; + +/** + * 문제:파티 + * 링크:https://www.acmicpc.net/problem/1238 + * + * 접근: + * 모든 정점간의 최단경로를 구하기 위해 플로이드 워샬 알고리즘을 사용 + * 각 학생들이 파티에 오고가는 최단 경로를 구해 비교 + * + * + * 시간복잡도: + * O(N^3) + * + * + * 소요 시간: + * 20m + * + */ +public class BJ_1238_파티 { + + public static void main(String[] args) { + final int INFINITE = 1000000; + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int M = sc.nextInt(); + int X = sc.nextInt(); + + int[][] dist = new int[N+1][N+1]; + + for (int i = 0; i < dist.length; i++) { + Arrays.fill(dist[i], INFINITE); + dist[i][i] = 0; + } + + for (int i = 0; i < M; i++) { + int from = sc.nextInt(); + int to = sc.nextInt(); + int time = sc.nextInt(); + + dist[from][to] = time; + } + + for (int k = 1; k <= N; k++) { + for (int i = 1; i <= N; i++) { + for (int j = 1; j <= N; j++) { + dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); + } + } + } + + int maxConsumingTime = 0; + + for (int i = 1; i < N+1; i++) { + int totalTime = dist[i][X] + dist[X][i]; + maxConsumingTime = Math.max(maxConsumingTime, totalTime); + } + + System.out.println(maxConsumingTime); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week18/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" new file mode 100644 index 0000000..f046b00 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week18/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" @@ -0,0 +1,146 @@ +package com.ssafy.algo.study.week18; + +import java.util.Scanner; + +/** + * 문제:주사위 굴리기 + * 링크:https://www.acmicpc.net/problem/14499 + * + * 접근: + * 1. 주사위를 클래스로 구성 + * 멤버 변수: 주사위의 위, 아래, 동,서,남,북 방향에 쓰여있는 숫자 + * 메소드: 위,아래, 좌, 우로 굴리기, 주사위 숫자 바꾸기 + * 2. 시뮬 구현 + * + * + * 시간복잡도: + * O(K) + * + * 소요 시간: + * 40m + * + */ +public class BJ_14499_주사위굴리기 { + + // 주사위 클래스 + static class Dice{ + // 주사위 6면에 쓰인숫자 저장 변수 + int top, bottom, east, west, north, south; + + public Dice(int top, int bottom, int east, int west, int north, int south) { + super(); + this.top = top; + this.bottom = bottom; + this.east = east; + this.west = west; + this.north = north; + this.south = south; + } + + public void rollDown(){ + int temp = this.bottom; + this.bottom = this.south; + this.south = this.top; + this.top = this.north; + this.north = temp; + } + + public void rollUp(){ + int temp = this.north; + this.north = this.top; + this.top = this.south; + this.south = this.bottom; + this.bottom = temp; + } + + public void rollLeft(){ + int temp = this.west; + this.west = this.top; + this.top = this.east; + this.east = this.bottom; + this.bottom = temp; + } + + public void rollRight(){ + int temp = this.east; + this.east = this.top; + this.top = this.west; + this.west = this.bottom; + this.bottom = temp; + } + + // 굴리기 + public void roll(int direction) { + switch(direction) { + case 1: + this.rollRight(); + break; + case 2: + this.rollLeft(); + break; + case 3: + this.rollUp(); + break; + case 4: + this.rollDown(); + break; + } + } + + // 주사위가 놓인 칸의 숫자를 입력으로 받아 주사위 바닥의 숫자 변경후 바뀌어야할 칸의 숫자 리턴 + public int mark(int numberOnBoard) { + if(numberOnBoard==0) { + return this.bottom; + }else { + this.bottom = numberOnBoard; + return 0; + } + } + + } + + static int[][] delta = {{0,0,0,-1,1},{0,1,-1,0,0}}; + static int N,M; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + M = sc.nextInt(); + int x = sc.nextInt(); + int y = sc.nextInt(); + int K = sc.nextInt(); + + int[][] board = new int[N][M]; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + board[i][j] = sc.nextInt(); + } + } + + // 주사위 객체 생성(0으로 초기화) + Dice dice = new Dice(0,0,0,0,0,0); + + for (int i = 0; i < K; i++) { + int input = sc.nextInt(); + + int newX = x + delta[0][input]; + int newY = y + delta[1][input]; + + // 주사위를 바깥으로 이동시키는 명령 무시 + if(!isValid(newX, newY)) continue; + + x = newX; + y = newY; + + dice.roll(input); // 주사위 굴리기 + board[x][y]=dice.mark(board[x][y]); // 주사위 바닥면과 칸의 숫자 변경 + System.out.println(dice.top); + } + } + private static boolean isValid(int newX, int newY) { + return newX>=0 && newX=0 && newY operator = new LinkedList<>(); + static List operand = new LinkedList<>(); + static int result = Integer.MIN_VALUE; + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(in.readLine()); + + String input = in.readLine(); + + for (int i = 0; i < input.length(); i++) { + char ch = input.charAt(i); + if(ch>='0' && ch<='9') { + operand.add(ch-'0'); + }else { + operator.add(ch); + } + } + + dfs(operand.get(0), 0); + + System.out.println(result); + } + private static void dfs(int sum, int idx) { + if(idx==operator.size()) { + result = Math.max(result, sum); + return; + } + + // 괄호 사용 x + int newSum = calc(operator.get(idx), sum, operand.get(idx+1)); + + dfs(newSum, idx+1); + + // 괄호 사용 + if(idx queue = new LinkedList<>(); + queue.add(new int[][]{r,b}); + int cnt=0; + + while(!queue.isEmpty()) { + + int size = queue.size(); + if(cnt==10) return -1; + + while(--size>=0) { + int[][] positions= queue.poll(); + + + for (int d = 0; d < 4; d++) { + int[] redMarblePosition = positions[0].clone(); + int[] blueMarblePosition = positions[1].clone(); + + // 어떤 구슬을 먼저 움직일지 선택 + String firstMarbleToMove = decideMarbleToMoveFirst(redMarblePosition, blueMarblePosition, d); + Result redMarbleResult = null; + Result blueMarbleResult = null; + + if(firstMarbleToMove.equals("redFirst")) { // 빨간 구슬 먼저 움직이는 경우 + redMarbleResult = rollMarble(redMarblePosition, blueMarblePosition, d); + blueMarbleResult = rollMarble(blueMarblePosition, redMarblePosition, d); + }else if(firstMarbleToMove.equals("blueFirst")) { // 파란 구슬 먼저 움직이는 경우 + blueMarbleResult = rollMarble(blueMarblePosition, redMarblePosition, d); + redMarbleResult = rollMarble(redMarblePosition, blueMarblePosition, d); + } + + if(blueMarbleResult.ended) // 파란구슬이 구멍으로 들어간 경우 + continue; + else if(redMarbleResult.ended) // 빨간구슬만 구멍으로 들어간 경우 + return cnt+1; + else if(!blueMarbleResult.moved && !redMarbleResult.moved) // 두구슬 모두 움직임이 없는 경우 + continue; + + queue.add(new int[][] {redMarblePosition, blueMarblePosition}); + } + } + cnt++; + } + + return -1; + } + + + // 빨간 구슬이 먼저 움직여야하는지 여부 파악 + private static String decideMarbleToMoveFirst(int[] redMarblePosition, int[] blueMarblePosition, int direction) { + + if(direction==0 && redMarblePosition[0]>blueMarblePosition[0]) { // 위로 기울였고 파란 구슬이 더 위쪽에 있는 경우 + return "blueFirst"; + }else if(direction==1 && redMarblePosition[1]>blueMarblePosition[1]) { // 왼쪽으로 기울였고 파란 구슬이 더 왼쪽에 있는 경우 + return "blueFirst"; + }else if(direction==2 && redMarblePosition[0]maxScore? score : maxScore; + return ; + } + + // 4번타자는 1번선수로 고정 + if(depth==3) { + batterSequence[depth] = 0; + permutation(depth+1, flag|1); + return; + } + + for (int i = 1; i < 9; i++) { + if((flag&(1<= distance) { // distance 이상의 거리가 확보되면 공유기 설치 + cnt++; + accDistance = 0; + } + } + + if (cnt >= C) { + answer = distance; + return true; + } else { + return false; + } + + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week19/BJ_2212_\354\204\274\354\204\234.java" "b/src/\354\235\264\354\240\225\354\210\230/week19/BJ_2212_\354\204\274\354\204\234.java" new file mode 100644 index 0000000..9dec354 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week19/BJ_2212_\354\204\274\354\204\234.java" @@ -0,0 +1,58 @@ +package com.ssafy.algo.study.week19; + +import java.util.Arrays; +import java.util.Collections; +import java.util.PriorityQueue; +import java.util.Scanner; + +/** + * 문제:센서 + * 링크:https://www.acmicpc.net/problem/2212 + * + * 접근: + * 하나의 집중국으로 모든 센서를 커버 하려면 수신가능 영역의 길이는 양끝에 위치한 센서사이의 거리입니다. + * 집중국이 하나 늘어나면 가장 거리가 먼 센서 사이의 공간을 비우고 각각의 집중국이 나머지 센서들이 위치한 길이를 커버해야합니다. + * 이렇게 K개의 집중국이 있으면 센서 사이의 공간을 K-1개만큼 커버하지 않을 수 있습니다. + * 센서 사이의 거리를 구하고 이를 오름차순 정렬하여 K-1개만큼 전체 길이에서 제외하면 답을 구할 수 있습니다. + * + * + * 시간복잡도: + * O(NlogN) + * + * 소요 시간: + * 20m + * + */ +public class BJ_2212_센서 { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int K = sc.nextInt(); + int[] sensors = new int[N]; + + for (int i = 0; i < N; i++) { + sensors[i] = sc.nextInt(); + } + + Arrays.sort(sensors); + PriorityQueue pq = new PriorityQueue(Collections.reverseOrder()); + + for (int i = 1; i < sensors.length; i++) { + pq.add(sensors[i] - sensors[i-1]); + } + + for (int i = 0; i < K-1; i++) { + pq.poll(); + } + + int ans = 0; + while(!pq.isEmpty()) { + ans += pq.poll(); + } + + System.out.println(ans); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week19/PG_64065_\355\212\234\355\224\214.java" "b/src/\354\235\264\354\240\225\354\210\230/week19/PG_64065_\355\212\234\355\224\214.java" new file mode 100644 index 0000000..1a281ac --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week19/PG_64065_\355\212\234\355\224\214.java" @@ -0,0 +1,71 @@ +package com.ssafy.algo.study.week19; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +/** + * 문제:튜플 + * 링크:https://programmers.co.kr/learn/courses/30/lessons/64065 + * + * 접근: + * 1. 파싱하여 정수형 이차원 배열로 변경 + * 2. 1차원 배열을 크기순서로 오름차순 배열 + * 3. 첫번째 인덱스부터 차례대로 확인하여 집합에 새로 추가된 숫자를 답안 배열에 추가 + * + * + * 시간복잡도: + * + * + * 소요 시간: + * 1h + * + */ +public class PG_64065_튜플 { + + public static void main(String[] args) { + System.out.println(Arrays.toString(solution("{{2},{2,1},{2,1,3},{2,1,3,4}}"))); + } + + static public int[] solution(String s) { + + String trimedS = s.substring(2, s.length()-2); // 양끝의 {{ 와 }} 제거 + String[] numbers = trimedS.split("},\\{"); // },{ 를 기준으로 split + + int[][] sets = new int[numbers.length][]; + + // 정수형 2차원 배열로 변경 + for (int i = 0; i < sets.length; i++) { + sets[i] = Arrays.stream(numbers[i].split(",")).mapToInt(Integer::parseInt).toArray(); + } + + // 1차원 배열의 크기순으로 정렬 + Arrays.sort(sets, new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + return o1.length - o2.length; + } + }); + + // 이미 확인한 숫자를 관리하기 위한 집합 + Set numberSet = new HashSet<>(); + + int[] answer = new int[sets.length]; // 답안 배열 + int idx =0; + + // 크기가 작은 배열부터 순서대로 확인하며 새로 나타나는 숫자를 답안 배열에 추가 + for (int[] set : sets) { + for (int number : set) { + if(!numberSet.contains(number)) { + answer[idx++] = number; + numberSet.add(number); + } + } + } + + + return answer; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week20/BJ_2533_SNS.java" "b/src/\354\235\264\354\240\225\354\210\230/week20/BJ_2533_SNS.java" new file mode 100644 index 0000000..ceb7a0b --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week20/BJ_2533_SNS.java" @@ -0,0 +1,70 @@ +package com.ssafy.algo.study.week20; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * 문제:사회망 서비스(SNS) + * 링크:https://www.acmicpc.net/problem/2533 + * + * 접근: + * + * + * 시간복잡도: + * + * + * 소요 시간: + * + */ +public class BJ_2533_SNS { + + + static List[] graph; + static int N; + static int[][] dp; + static boolean[] visited; + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + graph = new ArrayList[N+1]; + + for(int i = 1; i < N+1; i++) { + graph[i] = new ArrayList<>(); + } + + for (int i = 0; i < N-1; i++) { + + StringTokenizer st = new StringTokenizer(in.readLine()); + int u = Integer.parseInt(st.nextToken()); + int v = Integer.parseInt(st.nextToken()); + + graph[u].add(v); + graph[v].add(u); + } + + visited = new boolean[N+1]; + dp = new int[N+1][2]; + dfs(1); + System.out.println(Math.min(dp[1][0], dp[1][1])); + } + + private static void dfs(int i) { + visited[i] = true; + dp[i][0] = 0; + dp[i][1] = 1; + + for(int child: graph[i]) { + if(visited[child]) continue; + dfs(child); + dp[i][0] += dp[child][1]; + dp[i][1] += Math.min(dp[child][0], dp[child][1]); + } + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week21/BJ_11085_\352\265\260\354\202\254\354\235\264\353\217\231.java" "b/src/\354\235\264\354\240\225\354\210\230/week21/BJ_11085_\352\265\260\354\202\254\354\235\264\353\217\231.java" new file mode 100644 index 0000000..937b412 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week21/BJ_11085_\352\265\260\354\202\254\354\235\264\353\217\231.java" @@ -0,0 +1,95 @@ +package com.ssafy.algo.study.week21; + +import java.util.PriorityQueue; +import java.util.Scanner; + +/** + * 문제:군사 이동 + * 링크:https://www.acmicpc.net/problem/11085 + * + * 접근: + * 1. 엣지의 길이가 긴순서로 연결을 시도 + * 2. Union-find 알고리즘으로 서로소 집합 여부 판별 + * + * 시간복잡도: + * O(nlogn) + * + * + * 소요 시간: + * 1h + * + */ +public class BJ_11085_군사이동 { + + static class Edge implements Comparable{ + int start, end, width; + + public Edge(int start, int end, int width) { + super(); + this.start = start; + this.end = end; + this.width = width; + } + + @Override + public int compareTo(Edge o) { + return o.width - this.width; + } + + } + + static int parent[]; + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + int p = sc.nextInt(); + int w = sc.nextInt(); + int c = sc.nextInt(); + int v = sc.nextInt(); + + parent = new int[p]; + + for (int i = 0; i < p; i++) { + parent[i] = i; + } + + PriorityQueue pq = new PriorityQueue<>(); + + for (int i = 0; i < w; i++) { + int start = sc.nextInt(); + int end = sc.nextInt(); + int width = sc.nextInt(); + pq.add(new Edge(start, end, width)); + } + + while (!pq.isEmpty()) { + // 경로 추가 + Edge edge = pq.poll(); + union(edge.start, edge.end); + + if(find(c)==find(v)) { + System.out.println(edge.width); + return; + } + + } + } + + static int find(int a) { + if(parent[a]==a) return a; + return parent[a] = find(parent[a]); + } + + static boolean union(int a, int b) { + int rootA = find(a); + int rootB = find(b); + if(rootA!=rootB) { + parent[rootA] = rootB; + return true; + } + return false; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week21/BJ_1700_\353\251\200\355\213\260\355\203\255\354\212\244\354\274\200\354\245\264\353\247\201.java" "b/src/\354\235\264\354\240\225\354\210\230/week21/BJ_1700_\353\251\200\355\213\260\355\203\255\354\212\244\354\274\200\354\245\264\353\247\201.java" new file mode 100644 index 0000000..1dba571 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week21/BJ_1700_\353\251\200\355\213\260\355\203\255\354\212\244\354\274\200\354\245\264\353\247\201.java" @@ -0,0 +1,74 @@ +package com.ssafy.algo.study.week21; + +import java.util.HashSet; +import java.util.Scanner; +import java.util.Set; + +/** + * 문제:멀티탭 스케쥴링 + * 링크:https://www.acmicpc.net/problem/1700 + * + * 접근: + * OPT 알고리즘입니다. + * 앞으로 가장 오랫동안 사용되지 않을 전자제품을 교체합니다. + * + * + * 시간복잡도: + * + * + * 소요 시간: + * 2h + * + */ +public class BJ_1700_멀티탭스케쥴링 { + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int K = sc.nextInt(); + + int[] sequence = new int[K]; + + for (int i = 0; i < K; i++) { + sequence[i] = sc.nextInt(); + } + + int unplugCnt = 0; + Set multiTap = new HashSet<>(); + + for (int i = 0; i < K; i++) { + if(!multiTap.contains(sequence[i]) && multiTap.size()==N) { // 멀티탭에 안꽂혀있고 이미 멀티탭이 꽉찬 경우 + + // 교체할 전기용품 찾기 + int maxIdx = 0; + int selected= 0; + label: for (Integer product : multiTap) { + for (int j = i+1; j < K+1; j++) { + if(j==K) { // 다시 사용될 일이 없는 제품인 경우 + selected = product; + break label; + } + if(sequence[j]==product) { + if(maxIdxw) continue; // h는 w보다 클수 없음 + if(h==0) dp[w][h] = 1; // 초기 조건 + else dp[w][h] = dp[w-1][h] + dp[w][h-1]; + } + } + + int N = sc.nextInt(); + + while(N!=0) { + System.out.println(dp[N][N]); + N = sc.nextInt(); + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week21/PG_17686_\355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.java" "b/src/\354\235\264\354\240\225\354\210\230/week21/PG_17686_\355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.java" new file mode 100644 index 0000000..eb80f47 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week21/PG_17686_\355\214\214\354\235\274\353\252\205\354\240\225\353\240\254.java" @@ -0,0 +1,85 @@ +package com.ssafy.algo.study.week21; + +import java.util.Arrays; + +/** + * 문제:[3차]파일명 정렬 + * 링크:https://programmers.co.kr/learn/courses/30/lessons/17686 + * + * 접근: + * 1. 파일 클래스를 만들어 생성자로 head와 number 추출 + * 2. 조건에 맞춰 comparable을 implement하여 Arrays.sort() 사용 + * + * + * 시간복잡도: + * + * + * 소요 시간: + * 30m + * + */ +public class PG_17686_파일명정렬 { + + public static void main(String[] args) { + System.out.println(Arrays.toString(solution(new String[] {"img12"}))); + } + + static class File implements Comparable{ + String head; + int number; + String fileName; + + public File(String fileName) { + super(); + + int idx = 0; // 인덱스 + + // 숫자가 아닌 문자인 구간 확인 + while(!Character.isDigit(fileName.charAt(idx))) { + idx++; + } + this.head = fileName.substring(0, idx).toLowerCase(); + + int cnt = 0; // 숫자 개수 카운트 + int beginIdx = idx; // number 시작 인덱스 + + // 숫자 구간 확인 + while(idx{ + int from, to, weight; + + public Edge(int from, int to, int weight) { + super(); + this.from = from; + this.to = to; + this.weight = weight; + } + + @Override + public int compareTo(Edge o) { + return this.weight - o.weight; + } + + } + + static int[] parents; + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + int V = Integer.parseInt(st.nextToken()); + int E = Integer.parseInt(st.nextToken()); + + PriorityQueue pq = new PriorityQueue<>(); + + for (int i = 0; i < E; i++) { + st = new StringTokenizer(in.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int weight = Integer.parseInt(st.nextToken()); + pq.add(new Edge(from, to, weight)); + } + + // 서로소 집합 생성 + parents = new int[V+1]; + for (int i = 0; i < parents.length; i++) { + parents[i] = i; + } + + int cnt = 0; + int result = 0; + + while(cnt queue = new LinkedList<>(); + queue.add(N); + + boolean found = false; + int time = -1; + int cnt = 0; + boolean[] visited = new boolean[100001]; + + while(!found) { + int size = queue.size(); + time++; + + while(--size>=0) { + int current = queue.poll(); + visited[current] = true; + + if(current==K) { + found = true; + cnt++; + } + + // 걷기 + int next = current - 1; + if(next>=0 && !visited[next]) { + queue.add(next); + } + + next = current + 1; + if(next<=100000 && !visited[next]) { + queue.add(next); + } + + // 순간이동 + next = current*2; + if(next==current) continue; + if(next>=0 && next<=100000 && !visited[next]) { + queue.add(next); + } + } + } + + System.out.println(time); + System.out.println(cnt); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week22/BJ_14950_\354\240\225\353\263\265\354\236\220.java" "b/src/\354\235\264\354\240\225\354\210\230/week22/BJ_14950_\354\240\225\353\263\265\354\236\220.java" new file mode 100644 index 0000000..8de2aa5 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week22/BJ_14950_\354\240\225\353\263\265\354\236\220.java" @@ -0,0 +1,118 @@ +package com.ssafy.algo.study.week22; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +/** + * 문제: 정복자 + * 링크: https://www.acmicpc.net/problem/14950 + * + * 접근: + * 프림 알고리즘 + * 간선이 추가될때 마다 모든 간선의 크기를 K씩 증가시켜야함. + * + * + * 시간복잡도: + * + * + * 소요 시간: + * + */ +public class BJ_14950_정복자 { + + static class Node{ + int vertex, edge; + Node link; + public Node(int vertex,int edge, Node link) { + super(); + this.edge = edge; + this.vertex = vertex; + this.link = link; + } + @Override + public String toString() { + return "Node [vertex=" + vertex + ", edge=" + edge + ", link=" + link + "]"; + } + + + } + + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int t = Integer.parseInt(st.nextToken()); + + Node[] graph = new Node[N+1]; + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(in.readLine()); + int A = Integer.parseInt(st.nextToken()); + int B = Integer.parseInt(st.nextToken()); + int C = Integer.parseInt(st.nextToken()); + + graph[A] = new Node(B, C, graph[A]); + graph[B] = new Node(A, C, graph[B]); + } + + int answer = 0; + int cnt = 0; + int[] dist = new int[N+1]; + final int INF = Integer.MAX_VALUE; + boolean[] visited = new boolean[N+1]; + Arrays.fill(dist, INF); + + PriorityQueue pq = new PriorityQueue<>(new Comparator() { + + @Override + public int compare(int[] o1, int[] o2) { + return o1[1] - o2[1]; + } + + }); + + pq.add(new int[] {1, 0}); + dist[1] = 0; + + while(cntnode.edge) { + dist[node.vertex] = node.edge; + pq.add(new int[] {node.vertex, dist[node.vertex]}); + } + } + } + + System.out.println(answer); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week22/BJ_2933_\353\257\270\353\204\244\353\236\204.java" "b/src/\354\235\264\354\240\225\354\210\230/week22/BJ_2933_\353\257\270\353\204\244\353\236\204.java" new file mode 100644 index 0000000..08f64d1 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week22/BJ_2933_\353\257\270\353\204\244\353\236\204.java" @@ -0,0 +1,178 @@ +package com.ssafy.algo.study.week22; + +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; + +/** + * 문제: 미네랄 + * 링크: https://www.acmicpc.net/problem/2933 + * + * 접근: + * 1. + * + * + * 시간복잡도: + * + * + * 소요 시간: + * + */ +public class BJ_2933_미네랄 { + + static int R, C; + static char[][] map; + static boolean[][] visited; + static List cluster; + static int[][] delta = {{0,0,1,-1},{1,-1,0,0}}; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + R = sc.nextInt(); + C = sc.nextInt(); + + map = new char[R][C]; + + for (int i = 0; i < R; i++) { + String input = sc.next(); + map[i] = input.toCharArray(); + } + + int N = sc.nextInt(); + + for (int i = 0; i < N; i++) { + + int height = sc.nextInt(); + throwBar(i, height); + + } + + printMap(); + + } + + private static void dropCluster() { + // cluster 리스트 소팅 + cluster.sort(new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + if(o1[1]==o2[1]) { + return o2[0] - o1[0]; + } + return o1[1] - o2[1]; + } + }); + + // 각 열의 가장 아래 위치마다 가장 가까운 미네랄 혹은 땅의 위치 중 가장 짧은 거리 구하기 + int formerCol = -1; + int minDist = 100; + for (int i = 0; i < cluster.size(); i++) { + + if(formerCol != cluster.get(i)[1]) { // 열이 바뀔 때 마다 + formerCol = cluster.get(i)[1]; + int dist = getDistance(cluster.get(i)); + if(dist=0 && newRow=0 && newCol=0 && col(); + visited = new boolean[R][C]; + int newRow = row + delta[0][d]; + int newCol = col + delta[1][d]; + if(newRow>=0 && newRow=0 && newCol str1Map = new HashMap<>(); + Map str2Map = new HashMap<>(); + + // 대문자로 변경 + str1 = str1.toUpperCase(); + str2 = str2.toUpperCase(); + + // 다중집합 만들기 + for (int i = 0; i < str1.length()-1; i++) { + // 두 글자 모두 알파벳이면 + if(str1.charAt(i)>='A' && str1.charAt(i)<='Z' && str1.charAt(i+1)>='A' && str1.charAt(i+1)<='Z') { + String subString = str1.substring(i,i+2); + if(str1Map.containsKey(subString)) { + str1Map.put(subString, str1Map.get(subString)+1); + }else { + str1Map.put(subString, 1); + } + } + } + + for (int i = 0; i < str2.length()-1; i++) { + // 두 글자 모두 알파벳이면 + if(str2.charAt(i)>='A' && str2.charAt(i)<='Z' && str2.charAt(i+1)>='A' && str2.charAt(i+1)<='Z') { + String subString = str2.substring(i,i+2); + if(str2Map.containsKey(subString)) { + str2Map.put(subString, str2Map.get(subString)+1); + }else { + str2Map.put(subString, 1); + } + } + } + + // 둘다 공집합인 경우 + if(str1Map.size()==0 && str2Map.size()==0) { + return 65536; + } + + // 교집합 + int intersectionCnt = 0; + for (String key: str1Map.keySet()) { + if(str2Map.containsKey(key)) { + intersectionCnt += Math.min(str1Map.get(key), str2Map.get(key)); + } + } + + // 합집합 + int unionCnt = 0; + for (String key: str1Map.keySet()) { + if(str2Map.containsKey(key)) { + unionCnt += Math.max(str1Map.get(key), str2Map.get(key)); + }else { + unionCnt += str1Map.get(key); + } + } + + for (String key: str2Map.keySet()) { + if(!str1Map.containsKey(key)) { + unionCnt += str2Map.get(key); + } + } + + double similarity = ((double)intersectionCnt)/unionCnt; // 유사도 계산 + int answer = (int) Math.floor(similarity*65536); + return answer; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1043_\352\261\260\354\247\223\353\247\220.java" "b/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1043_\352\261\260\354\247\223\353\247\220.java" new file mode 100644 index 0000000..2212db5 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1043_\352\261\260\354\247\223\353\247\220.java" @@ -0,0 +1,94 @@ +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; + +public class BJ_1043_거짓말 { + + static int[] people; + static List[] parties; + static int answer=0, M, N; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + M = sc.nextInt(); + + int numberOfPeopleWhoKnowsTruth = sc.nextInt(); + + people = new int[N+1]; + parties = new List[M]; + + for (int i = 0; i < numberOfPeopleWhoKnowsTruth; i++) { + people[sc.nextInt()] = 1; + } + + for (int i = 0; i < M; i++) { + parties[i] = new LinkedList<>(); + int numberOfParticipants = sc.nextInt(); + + for (int j = 0; j < numberOfParticipants; j++) { + parties[i].add(sc.nextInt()); + } + + } + + dfs(0, 0); + + System.out.println(answer); + + } + + private static void dfs(int depth, int numberOfLies) { + + if(depth==M){ + answer = Math.max(answer, numberOfLies); + return; + } + + int[] temp = Arrays.copyOf(people, N+1); + int truth = 0; + int fake = 0; + + for (int participant : + parties[depth]) { + + if(people[participant]==1){ + truth++; + }else if(people[participant]==2){ + fake++; + } + + } + + // 불가능한 경우 + if(truth>0 && fake>0){ + return; + } + + // 진실 말하기 + if(fake==0){ + for (int participant : + parties[depth]) { + people[participant] = 1; + } + + dfs(depth+1, numberOfLies); + } + + people = Arrays.copyOf(temp, N+1); + + // 과장하기 + if(truth==0){ + for (int participant : + parties[depth]) { + people[participant] = 2; + } + + dfs(depth+1, numberOfLies+1); + } + + people = Arrays.copyOf(temp, N+1); + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.java" "b/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.java" new file mode 100644 index 0000000..d0d062d --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week23/BJ_1194_\353\213\254\354\235\264\354\260\250\354\230\244\353\245\270\353\213\244\352\260\200\354\236\220.java" @@ -0,0 +1,115 @@ +package com.ssafy.algo.study.week23; + +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + +/** + * 문제: 달이 차오른다, 가자. + * 링크: https://www.acmicpc.net/problem/1194 + * + * 접근: + * 1. 현재 소지하고 있는 열쇠를 비트마스킹으로 표현하여 가지고 있는 열쇠 조합에 따라 방문 여부 배열을 3차원으로 구성 + * map[현재가지고 있는 열쇠조합의 비트마스크][행][열] + * + * + * 시간복잡도: + * + * + * 소요 시간: + * 30m + * + */ +public class BJ_1194_달이차오른다가자 { + + static int N,M; + static boolean[][][] visited; + static char[][] map; + static int[][] delta = {{0,0,-1,1,},{-1,1,0,0}}; // 좌 우 상 하 + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); // 행 + M = sc.nextInt(); // 열 + + map = new char[N][M]; // 맵 + visited = new boolean[1<<6][N][M]; // 가지고 있는 열쇠조합에 따른 방문여부 표시 2차원 배열 + + int row = -1; + int col = -1; + + for (int i = 0; i < N; i++) { + map[i] = sc.next().toCharArray(); + + for (int j = 0; j < M; j++) { + if(map[i][j]=='0') { + row = i; + col = j; + map[i][j]='.'; + } + } + } + + int result =bfs(row, col); + + System.out.println(result); + } + + private static int bfs(int y, int x) { + Queue queue = new LinkedList<>(); + + queue.add(new int[] {y, x, 0}); + int cnt = 0; // 이동 횟수 + + while(!queue.isEmpty()) { + + int size = queue.size(); + + while(--size>=0) { + + int[] currentState = queue.poll(); + + int row = currentState[0]; + int col = currentState[1]; + int keyState = currentState[2]; + + // 탈출 조건 + if(map[row][col]=='1') return cnt; + + // 열쇠를 획득한 경우 + if(map[row][col]>='a' && map[row][col]<='f') { + keyState = keyState | (1<< (map[row][col] - 'a')); + } + + for (int d = 0; d < 4; d++) { + + int newRow = row + delta[0][d]; + int newCol = col + delta[1][d]; + + if(isValid(newRow, newCol, keyState)) { + + // 다음 위치가 문이면서 문에 해당하는 키가 없으면 이동 불가능 + if(map[newRow][newCol]>='A' && map[newRow][newCol]<='F' + && (keyState & 1<<(map[newRow][newCol]-'A'))==0) { + continue; + } + + visited[keyState][newRow][newCol] = true; // 방문 처리 + queue.add(new int[] {newRow, newCol, keyState}); + } + + } + } + cnt++; + } + + return -1; + } + + // 다음 위치로 이동가능한지 확인 + private static boolean isValid(int newRow, int newCol, int keyState) { + return newRow>=0 && newRow=0 && newCol0){ + + ///////////////////////////////////////////////////////// Ʈ ȸ + + + if(off==0){ + off = 2*N -1; + }else{ + off --; + } + + if(on==0){ + on = 2*N -1; + }else{ + on--; + } + + belt[off].isRobotOn = false; // κ + + ///////////////////////////////////////////////////////// κ ̵ + if(on on ; i--) { + // ĭ κ 0 ũ ĭ κ + if(!belt[i].isRobotOn && belt[i].durability>0 && belt[i-1].isRobotOn){ + // ĭ κ ĭ ̵ + belt[i-1].isRobotOn = false; + belt[i].isRobotOn = true; + belt[i].durability--; + if(belt[i].durability==0) { + K--; + } + } + } + }else{ + for (int i = off; i > 0; i--) { + // ĭ κ 0 ũ ĭ κ + if(!belt[i].isRobotOn && belt[i].durability>0 && belt[i-1].isRobotOn){ + // ĭ κ ĭ ̵ + belt[i-1].isRobotOn = false; + belt[i].isRobotOn = true; + belt[i].durability--; + if(belt[i].durability==0) { + K--; + } + } + } + // ĭ κ 0 ũ ĭ κ + if(!belt[0].isRobotOn && belt[0].durability>0 && belt[2*N-1].isRobotOn){ + // ĭ κ ĭ ̵ + belt[2*N-1].isRobotOn = false; + belt[0].isRobotOn = true; + belt[0].durability--; + if(belt[0].durability==0) { + K--; + } + } + for (int i = 2*N-1; i > on; i--) { + // ĭ κ 0 ũ ĭ κ + if(!belt[i].isRobotOn && belt[i].durability>0 && belt[i-1].isRobotOn){ + // ĭ κ ĭ ̵ + belt[i-1].isRobotOn = false; + belt[i].isRobotOn = true; + belt[i].durability--; + if(belt[i].durability==0) { + K--; + } + } + } + } + + belt[off].isRobotOn = false; // κ + + ////////////////////////////////////////////////////// κ ø + if(belt[on].durability>0){ + belt[on].isRobotOn = true; + belt[on].durability--; + if(belt[on].durability==0) { + K--; + } + } + cnt++; + + } + + System.out.println(cnt); + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week24/PG_42885_\352\265\254\353\252\205\353\263\264\355\212\270.java" "b/src/\354\235\264\354\240\225\354\210\230/week24/PG_42885_\352\265\254\353\252\205\353\263\264\355\212\270.java" new file mode 100644 index 0000000..5a8a855 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week24/PG_42885_\352\265\254\353\252\205\353\263\264\355\212\270.java" @@ -0,0 +1,51 @@ +package week24; + +import java.util.Arrays; + +/** + * : Ʈ + * ũ: https://programmers.co.kr/learn/courses/30/lessons/42885 + * + * Ǯ: + * 1. + * 2. ʳ ε Ͽ ġ limit Ѵ ¿ + * ƴ ſ ¿ + * + * + * ð⵵: + * O(N) + * + * Ǯ̿ ɸ ð: + * 20m + * + */ + +public class PG_42885_Ʈ { + + public static void main(String[] args) { + System.out.println(solution(new int[] {70, 80, 50}, 100)); + } + + static public int solution(int[] people, int limit) { + + int left = 0; + int right = people.length-1; + + Arrays.sort(people); + + int numberOfBoat = 0; + + while(left<=right) { + if(people[left]+ people[right]<=limit) { + left++; + right--; + }else { + right--; + } + numberOfBoat++; + } + + return numberOfBoat; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week24/PG_67259_\352\262\275\354\243\274\353\241\234\352\261\264\354\204\244.java" "b/src/\354\235\264\354\240\225\354\210\230/week24/PG_67259_\352\262\275\354\243\274\353\241\234\352\261\264\354\204\244.java" new file mode 100644 index 0000000..51a53fd --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week24/PG_67259_\352\262\275\354\243\274\353\241\234\352\261\264\354\204\244.java" @@ -0,0 +1,67 @@ +package week24; + +import java.util.*; +class PG_67259_ַΰǼ { + + public static void main(String[] args) { + System.out.println(solution(new int[][] {{0,0,0},{0,0,0},{0,0,0}})); + } + public static int solution(int[][] board) { + int min = Integer.MAX_VALUE; // ּ + int[][] delt = {{-1,1,0,0},{0,0,-1,1}}; // 4 delta + int N = board.length; // ũ + + int[][][] visited = new int[4][N][N]; // 湮 ó 迭 + for (int i = 0; i < visited.length; i++) { + for (int j = 0; j < N; j++) { + for (int k = 0; k < N; k++) { + visited[i][j][k] = Integer.MAX_VALUE; + } + } + } + Queue queue = new LinkedList<>(); + + + queue.add(new int[] {0,0,-1,0}); // 0,0 + + while(!queue.isEmpty()) { + int[] current = queue.poll(); + int r = current[0]; + int c = current[1]; + int postDirection = current[2]; + int cost = current[3]; + + if(r==N-1 && c==N-1) {// + min = Math.min(min, cost); + continue; // ٸ Ƿ + } + + for (int d = 0; d < 4; d++) { + int nr=r+delt[0][d]; + int nc=c+delt[1][d]; + int newCost = cost; + + if(!isValid(nr, nc, board)) continue; // ȿ ġ õ X + + if(postDirection==-1) { // ġ + newCost += 100; + }else if(postDirection==d) { // + newCost += 100; + }else {// ٸ ڳ + + newCost += 600; + } + + if(visited[d][nr][nc]>=newCost) { // ó ԰ų ̹ ͺ + queue.add(new int[] {nr,nc,d,newCost}); + visited[d][nr][nc] = newCost; + } + } + } + + return min; + } + + private static boolean isValid(int nr, int nc, int[][] board) { + return nr>=0 && nc>=0 && nr map = new HashMap<>(); // ڽ丮 + static List temp, list = new LinkedList<>(); + + static public String[] solution(String[] orders, int[] course) { + + // ڽ丮 ĺ + for (String order : orders) { + for (int numberOfMenu : course) { + comb(order, 0, 0, numberOfMenu, ""); + } + } + + + for (int numberOfMenu : course) {// ڽ丮 Ե ǰ + + temp = new LinkedList<>(); // ӽú + int max = 0; + + for (Map.Entry entry : map.entrySet()) { // ڽ丮 ĺ + + if(entry.getKey().length()==numberOfMenu) { // ȮϷϴ ǰ شϴ ĺ̸ + + if(max1) { // ݱ Ȯߴ ĺڽ麸 󵵰 1̻ + temp = new LinkedList<>(); // temp ʱȭ ߰ + temp.add(entry.getKey()); + max = entry.getValue(); + + }else if(max==entry.getValue()) { // Բ ֹ ޴ , 迭 + temp.add(entry.getKey()); + } + + } + + } + + // ̾Ƴ ڽ丮 Ʈ + for (String i : temp) { + list.add(i); + } + } + + // 迭 + String[] answer = new String[list.size()]; + for (int i = 0; i < answer.length; i++) { + answer[i] = list.get(i); + } + Arrays.sort(answer); + return answer; + } + + + + private static void comb(String order, int depth, int start, int numberOfMenu, String result) { + + if(depth==numberOfMenu) { + result = sortAsc(result); + if(!map.containsKey(result)) { + map.put(result, 1); + }else { + map.replace(result, map.get(result)+1); + } + return; + } + + for (int i = start; i < order.length(); i++) { + comb(order, depth+1, i+1, numberOfMenu, result + order.charAt(i)); + } + + } + + // ڿ + static String sortAsc(String str) { + char[] arr = str.toCharArray(); + Arrays.sort(arr); + return new String(arr); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\250.java" "b/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\250.java" new file mode 100644 index 0000000..4c2be8e --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\250.java" @@ -0,0 +1,67 @@ +package week25; + +import java.util.Scanner; + +/** + * : + * ũ: https://www.acmicpc.net/problem/1107 + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_1107_ { + + static int min, N, digitsCnt; + static int[] buttons; + static boolean[] isBroke = new boolean[10]; + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + int M = sc.nextInt(); + + // ڸ ϱ + digitsCnt = Integer.toString(N).length(); + + // 峭 ư ϱ + for (int i = 0; i < M; i++) { + + isBroke[sc.nextInt()] = true; + + } + + // 100 äο +- ư ϴ + min = Math.abs(100 - N); + + // ߺ + permutationWithRepition(0, 0); + + System.out.println(min); + } + + + // ߺ + private static void permutationWithRepition(int depth, int result) { + + if(depth>=digitsCnt-1) { + min = Math.min(min, Integer.toString(result).length() + Math.abs(N - result)); // ּ Ƚ + if(depth==digitsCnt+1) return; + } + + for (int i = 0; i < 10; i++) { + if(isBroke[i]) continue; + permutationWithRepition(depth+1, (result*10)+i); + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\2502.java" "b/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\2502.java" new file mode 100644 index 0000000..fd86e5e --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week25/BJ_1107_\353\246\254\353\252\250\354\273\2502.java" @@ -0,0 +1,65 @@ +package week25; + +import java.util.Scanner; + +/** + * : + * ũ: https://www.acmicpc.net/problem/1107 + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_1107_2 { + + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int M = sc.nextInt(); + + // ڸ ϱ + int digitsCnt = Integer.toString(N).length(); + + boolean[] isBroke = new boolean[10]; + + // 峭 ư ϱ + for (int i = 0; i < M; i++) { + + isBroke[sc.nextInt()] = true; + + } + + // 100 äο +- ư ϴ + int min = Math.abs(100 - N); + + String[] buttons = {"0","1","2","3","4","5","6","7","8","9"}; + + for (int i = 0; i < 999999; i++) { + boolean flag = false; + String numberInStr = Integer.toString(i); + for (int j = 0; j < 10; j++) { + if(isBroke[j] && numberInStr.contains(buttons[j])) { + flag= true; + break; + } + } + if(flag) continue; + + min = Math.min(min, numberInStr.length() + Math.abs(N-i)); + } + + + System.out.println(min); + } + + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week25/PG42578_\354\234\204\354\236\245.java" "b/src/\354\235\264\354\240\225\354\210\230/week25/PG42578_\354\234\204\354\236\245.java" new file mode 100644 index 0000000..e9ef8e8 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week25/PG42578_\354\234\204\354\236\245.java" @@ -0,0 +1,36 @@ +package week25; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class PG42578_ { + + public static void main(String[] args) { + System.out.println(solution(new String[][] {{"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"}})); + } + + static public int solution(String[][] clothes) { + + Map map = new HashMap<>(); + + for (String[] clothe : clothes) { + String name = clothe[0]; + String type = clothe[1]; + if(map.containsKey(type)) { + map.put(type, map.get(type)+1); + }else { + map.put(type, 1); + } + } + + int answer = 1; + + for (Entry entry : map.entrySet()) { + answer *= (entry.getValue() + 1); + } + + return --answer; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week25/PG_17684_\354\225\225\354\266\225.java" "b/src/\354\235\264\354\240\225\354\210\230/week25/PG_17684_\354\225\225\354\266\225.java" new file mode 100644 index 0000000..2fc9b31 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week25/PG_17684_\354\225\225\354\266\225.java" @@ -0,0 +1,85 @@ +package week25; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class PG_17684_ { + + public static void main(String[] args) { + System.out.println(Arrays.toString(solution("ABABABABABABABAB"))); + } + + static public int[] solution(String msg) { + + Map map = new HashMap<>() {{ + put("A",1); + put("B",2); + put("C",3); + put("D",4); + put("E",5); + put("F",6); + put("G",7); + put("H",8); + put("I",9); + put("J",10); + put("K",11); + put("L",12); + put("M",13); + put("N",14); + put("O",15); + put("P",16); + put("Q",17); + put("R",18); + put("S",19); + put("T",20); + put("U",21); + put("V",22); + put("W",23); + put("X",24); + put("Y",25); + put("Z",26); + }}; + + int startPoint = 0; + int maxLen = 1; + int newIdx = 27; + + List ansList = new LinkedList<>(); + + while(startPointi).toArray(); + return answer; + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week25/PG_92343_\354\226\221\352\263\274\353\212\221\353\214\2002.java" "b/src/\354\235\264\354\240\225\354\210\230/week25/PG_92343_\354\226\221\352\263\274\353\212\221\353\214\2002.java" new file mode 100644 index 0000000..7a30cb9 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week25/PG_92343_\354\226\221\352\263\274\353\212\221\353\214\2002.java" @@ -0,0 +1,66 @@ +package week25; + +import java.util.LinkedList; +import java.util.List; + +public class PG_92343_2 { + + public static void main(String[] args) { + System.out.println(solution(new int[] {0,0,1,1,1,0,1,0,1,0,1,1}, new int[][] {{0,1},{1,2},{1,4},{0,8},{8,7},{9,10},{9,11},{4,3},{6,5},{4,6},{8,9}})); + } + + static List[] childs; + static int[] Info; + static int max = 0; + + static public int solution(int[] info, int[][] edges) { + + childs = new List[info.length]; + Info = info; + + for (int i = 0; i < edges.length; i++) { + + int parent = edges[i][0]; + int child = edges[i][1]; + + if(childs[parent]==null) { + childs[parent] = new LinkedList(); + } + + childs[parent].add(child); + } + + List list= new LinkedList(); + list.add(0); + traversal(0, 0, 0, list); + return max; + } + + private static void traversal(int currentNode, int sheepCnt, int wolfCnt, List postChilds) { + + // Ȥ ߰ + if(Info[currentNode]==0) sheepCnt++; + else wolfCnt++; + + if(wolfCnt>=sheepCnt) return; // Ұ + + max = Math.max(max, sheepCnt); + + // Ž ġ ĺ ϱ + List nextNodes = new LinkedList(); + nextNodes.addAll(postChilds); + + nextNodes.remove(Integer.valueOf(currentNode)); // + + if(childs[currentNode]!=null) { + for (int child : childs[currentNode]) { // ڽ + nextNodes.add(child); + } + } + + for (int nextNode : nextNodes) { + traversal(nextNode, sheepCnt, wolfCnt, nextNodes); + } + + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week26/BJ_15684_\354\202\254\353\213\244\353\246\254\354\241\260\354\236\221.java" "b/src/\354\235\264\354\240\225\354\210\230/week26/BJ_15684_\354\202\254\353\213\244\353\246\254\354\241\260\354\236\221.java" new file mode 100644 index 0000000..9706e3c --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week26/BJ_15684_\354\202\254\353\213\244\353\246\254\354\241\260\354\236\221.java" @@ -0,0 +1,135 @@ +package week26; + +import java.util.Scanner; + + +public class BJ_15684_ٸ { + + static int N, M, H; + static boolean[][] ladder; + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + M = sc.nextInt(); + H = sc.nextInt(); + + int[] crossCnt = new int[N+1]; + ladder = new boolean[H+1][N+1]; + + for (int i = 0; i < M; i++) { + + int a = sc.nextInt(); + int b = sc.nextInt(); + + crossCnt[b]++; + + ladder[a][b]=true; + + } + + + // Ȧ 3 ʰ Ұ + int cnt=0; + for (int cross : crossCnt) { + if(cross%2==1) { + cnt++; + } + } + + if(cnt>3) { + System.out.println(-1); + return; + } + + int lines = 0; + for (; lines < 4; lines++) { + if(dfs(1, 1, 0, lines)) break; + } + + lines = lines>3?-1:lines; // 3̸̻ Ұ + System.out.println(lines); + } + + private static boolean dfs(int startRow, int startCol, int depth, int lines) { + + if(depth==lines) { // μ ϸ + return isCorrect(ladder); + } + + int row = startRow-1; + for (int col = startCol; col < N; col++) { + + while(++row<=H) { + // ̹ μ Ұ + if(ladder[row][col]) { + continue; + } + + // ʿ μ Ұ + if(ladder[row][col-1]) { + continue; + } + + // ʿ μ Ұ + if(ladder[row][col+1]) { + continue; + } + + // μ + ladder[row][col] = true; + + if(row0 && ladder[row][col-1]){ // + col--; + } + + row++; + + } + + if(vLine != col) { + return false; + } + + } + + return true; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week26/BJ_2075_N\353\262\210\354\247\270\355\201\260\354\210\230.java" "b/src/\354\235\264\354\240\225\354\210\230/week26/BJ_2075_N\353\262\210\354\247\270\355\201\260\354\210\230.java" new file mode 100644 index 0000000..cf0ab88 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week26/BJ_2075_N\353\262\210\354\247\270\355\201\260\354\210\230.java" @@ -0,0 +1,51 @@ +package week26; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + +/** + * : N° ū + * ũ: https://www.acmicpc.net/problem/2075 + * + * Ǯ: + * ڷᱸ ũ + * + * ð⵵: + * O(NlogN) + * + * Ǯ̿ ɸ ð: + * 30min + * + */ +public class BJ_2075_N°ū { + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(in.readLine()); + StringTokenizer st; + + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(in.readLine()); + for (int j = 0; j < N; j++) { + pq.add(Integer.parseInt(st.nextToken())); + } + } + + for (int i = 0; i < N-1; i++) { + pq.poll(); + } + + System.out.println(pq.poll()); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week26/PG_42626_\353\215\224\353\247\265\352\262\214.java" "b/src/\354\235\264\354\240\225\354\210\230/week26/PG_42626_\353\215\224\353\247\265\352\262\214.java" new file mode 100644 index 0000000..e801701 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week26/PG_42626_\353\215\224\353\247\265\352\262\214.java" @@ -0,0 +1,60 @@ +package week26; + +import java.util.PriorityQueue; + +/** + * : ʰ + * ũ: https://programmers.co.kr/learn/courses/30/lessons/42626 + * + * Ǯ: + * ڷᱸ pq ں + * ں k̻ ɶ + * pq ΰ ο ϱ + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class PG_42626_ʰ { + + public static void main(String[] args) { + System.out.println(solution(new int[] {1, 2, 3, 9, 10, 12}, 7)); + } + + static public int solution(int[] scoville, int K) { + + int numberOfFoodBelowK = 0; + PriorityQueue pq = new PriorityQueue<>(); + + // pq ʱȭ + for (int i = 0; i < scoville.length; i++) { + int scovilleOfFood = scoville[i]; + if(scovilleOfFood0 && pq.size()>1) { // k ְ 1 + int sum = pq.poll() + pq.poll()*2; + if(sum>=K) { + numberOfFoodBelowK -=2; + }else { + numberOfFoodBelowK--; + } + + pq.add(sum); + cnt++; + } + + if(numberOfFoodBelowK>0) return -1; + + return cnt; + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week26/PG_92342_\354\226\221\352\266\201\353\214\200\355\232\214.java" "b/src/\354\235\264\354\240\225\354\210\230/week26/PG_92342_\354\226\221\352\266\201\353\214\200\355\232\214.java" new file mode 100644 index 0000000..ef538d1 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week26/PG_92342_\354\226\221\352\266\201\353\214\200\355\232\214.java" @@ -0,0 +1,100 @@ +package week26; + +import java.util.Arrays; + +/** + * : ôȸ + * ũ: https://programmers.co.kr/learn/courses/30/lessons/92342 + * + * Ǯ: + * Ž + * + * + * ð⵵: + * ? + * + * Ǯ̿ ɸ ð: + * 4h + * + */ +public class PG_92342_ôȸ { + + public static void main(String[] args) { + System.out.println(Arrays.toString(solution(5, new int[] {2,1,1,1,0,0,0,0,0,0,0}))); + } + + static int[] result = {-1}; + static int N, maxScoreDiff = 0; + static int[] Info; + public static int[] solution(int n, int[] info) { + + Info = info; + N = n; // ȭ n + + dfs(0,0, new int[] {0,0,0,0,0,0,0,0,0,0,0}); // 10, 9, 8 ..., 0 + + return result; + + } + + private static void dfs(int depth, int arrowCnt, int[] record) { + + if(depth==10) { // ῡ ȭ Ƚ + record[10] = N - arrowCnt; + if(result[0]==4) { + System.out.println(Arrays.toString(result)); + } + // + int[] scores = calcScore(record); + int scoreDiff = scores[1]-scores[0]; + + if(scoreDiff>0) {// ̰ + + if(maxScoreDiff= 0; i--) { + if(record[i]>result[i]) { + result = Arrays.copyOf(record, record.length); + break; + }else if(record[i]0) cnt++; + } + } + + return cnt; + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week27/BJ_10026_\354\240\201\353\241\235\354\203\211\354\225\275.java" "b/src/\354\235\264\354\240\225\354\210\230/week27/BJ_10026_\354\240\201\353\241\235\354\203\211\354\225\275.java" new file mode 100644 index 0000000..04983c2 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week27/BJ_10026_\354\240\201\353\241\235\354\203\211\354\225\275.java" @@ -0,0 +1,100 @@ +package week27; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * : ϻ + * ũ: https://www.acmicpc.net/problem/10026 + * + * Ǯ: + * dfs ι Ͽ ã + * ϻ ʷϻ + * + * + * ð⵵: + * O(N^2) + * + * Ǯ̿ ɸ ð: + * 30m + * + */ +public class BJ_10026_ϻ { + + static int[][] delta = {{0,0,-1,1},{-1,1,0,0}}; + static boolean[][] visited; + static int N, normalCnt, colorBlindCnt; + static char[][] map; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + map = new char[N][N]; + visited = new boolean[N][N]; + + for (int i = 0; i < N; i++) { + map[i] = in.readLine().toCharArray(); + } + + // ÷ īƮ + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if(!visited[i][j]) { + dfs(new char[] {map[i][j]}, i,j); + normalCnt++; + } + } + } + + + // ϻ īƮ + visited = new boolean[N][N]; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if(!visited[i][j]) { + if(map[i][j]=='B') { + dfs(new char[] {map[i][j]}, i,j); + }else { + dfs(new char[] {'R','G'}, i,j); + } + colorBlindCnt++; + } + } + } + + System.out.println(normalCnt + " " + colorBlindCnt); + + + + } + + private static void dfs(char[] candidates, int row, int col) { + + visited[row][col] = true; + + for (int d = 0; d < 4; d++) { + int newRow = row + delta[0][d]; + int newCol = col + delta[1][d]; + + // ȿ ڸ ƴϸ ŵ + if(!(newRow>=0 && newCol>=0 && newRow=0 && newCol>=0 && newRow0; startDay--) { + int aDayAfterendDay = startDay + T[startDay]; + + if(aDayAfterendDay>N+1) { + dp[startDay] =dp[startDay+1]; + continue; + + } + + dp[startDay] = Math.max(dp[startDay+1], P[startDay] + dp[aDayAfterendDay]); + } + + System.out.println(dp[1]); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week27/BJ_2473_\354\232\251\354\225\241.java" "b/src/\354\235\264\354\240\225\354\210\230/week27/BJ_2473_\354\232\251\354\225\241.java" new file mode 100644 index 0000000..0a80cd9 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week27/BJ_2473_\354\232\251\354\225\241.java" @@ -0,0 +1,134 @@ +package week27; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/2473 + * + * Ǯ: + * Ư + * Ž + * ϳ ̺Ž õ + * + * + * ð⵵: + * O(NlogN) + * + * Ǯ̿ ɸ ð: + * 2h + * + */ +public class BJ_2473_ { + + static int N; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + int[] solutions = new int[N]; + StringTokenizer st = new StringTokenizer(in.readLine()); + + for (int i = 0; i < N; i++) { + solutions[i] = Integer.parseInt(st.nextToken()); + } + + // + Arrays.parallelSort(solutions); + + int[] ans = {0,0,0}; + long min = Long.MAX_VALUE; // Ư 밪 ּҰ + + int[] delta = {-2,-1,1,2}; + int[] delta2 = {-2,-1,0,1,2}; + + label: for (int i = 0; i < N-1; i++) {// a + int a = solutions[i]; + for (int j = i+1; j < N; j++) {// b + + int b = solutions[j]; + + int target = -a-b; // 0̵Ǵ Ư + + // ̺Ž ִ ã + int targetIdx = Arrays.binarySearch(solutions, target); + + // ϴ + if(targetIdx>=0) { + + if(targetIdx==i || targetIdx==j) { // ̹ + + // 翷 ĭ Ȯ + for (int d = 0; d < 4; d++) { + + int nextIdx = targetIdx + delta[d]; + + if(!isValid(nextIdx, i, j)) { + continue; + } + + long sum = (long)a+b+solutions[nextIdx]; + if(sum<0) { + sum *=-1; + } + + if(min>sum) { + min = sum; + ans = new int[] {a,b,solutions[nextIdx]}; + } + + } + }else { // Ư 0 Ǵ + + min = 0; + ans = new int[] {a,b,target}; + break label; + + } + + }else {// + + // 翷 ĭ Ȯ + for (int d = 0; d < 5; d++) { + + int nextIdx = (targetIdx*-1) - 1 + delta2[d]; + + if(!isValid(nextIdx, i, j)) { + continue; + } + + long sum = (long)a+b+solutions[nextIdx]; + if(sum<0) { + sum *=-1; + } + + if(min>sum) { + min = sum; + ans = new int[] {a,b,solutions[nextIdx]}; + } + + } + + } + } + } + + Arrays.sort(ans); + + System.out.println(ans[0]+" "+ans[1]+" "+ans[2]); + + } + + + // 밡 ġ Ȯ + private static boolean isValid(int idx, int i, int j) { + return idx>=0 && idx deque = new ArrayDeque(); + + for (int i = 0; i < N; i++) { + + A[i] = Integer.parseInt(st.nextToken()); + + // dequeȿ ִ ִ + while(!deque.isEmpty() && deque.peekLast()[0]>=A[i]) { + deque.pollLast(); + } + + deque.offer(new int[] {A[i], i}); + + while(deque.peek()[1]<=i-L) { // ̵ Ѵ + deque.poll(); + } + + int D = deque.peek()[0]; + + sb.append(D + " "); + + } + + System.out.println(sb.toString()); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week28/BJ_11003_\354\265\234\354\206\237\352\260\222\354\260\276\352\270\260_pq.java" "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_11003_\354\265\234\354\206\237\352\260\222\354\260\276\352\270\260_pq.java" new file mode 100644 index 0000000..5e51d04 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_11003_\354\265\234\354\206\237\352\260\222\354\260\276\352\270\260_pq.java" @@ -0,0 +1,68 @@ +package week28; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Comparator; +import java.util.PriorityQueue; +import java.util.StringTokenizer; + + +/** + * : ּڰ ã + * ũ: https://www.acmicpc.net/problem/11003 + * + * Ǯ: + * pq .. ðʰ... + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_11003_ּڰã_pq { + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int L = Integer.parseInt(st.nextToken()); + + int[] A = new int[N]; + st = new StringTokenizer(in.readLine()); + PriorityQueue pq = new PriorityQueue<>(new Comparator() { + + @Override + public int compare(int[] o1, int[] o2) { + return o1[0] - o2[0]; + } + + }); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < N; i++) { + + A[i] = Integer.parseInt(st.nextToken()); + pq.add(new int[] {A[i], i}); + + + while(pq.peek()[1]<=i-L) { + pq.poll(); + } + + int D = pq.peek()[0]; + + sb.append(D + " "); + + } + + System.out.println(sb.toString()); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week28/BJ_12912_\355\212\270\353\246\254\354\210\230\354\240\225.java" "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_12912_\355\212\270\353\246\254\354\210\230\354\240\225.java" new file mode 100644 index 0000000..6870895 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_12912_\355\212\270\353\246\254\354\210\230\354\240\225.java" @@ -0,0 +1,106 @@ +package week28; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : Ʈ + * ũ: https://www.acmicpc.net/problem/12912 + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_12912_Ʈ { + + static int max = 0; + static int[][] adjMatrix; + static int N; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + adjMatrix = new int[N][N]; + int[][] logs = new int[N][]; + + StringTokenizer st; + for (int i = 0; i < N-1; i++) { + st = new StringTokenizer(in.readLine()); + int from = Integer.parseInt(st.nextToken()); + int to = Integer.parseInt(st.nextToken()); + int weight = Integer.parseInt(st.nextToken()); + + adjMatrix[from][to] = adjMatrix[to][from] = weight; + logs[i] = new int[] {from, to, weight}; + } + + + // ϳ غ + for (int i = 0; i < N-1; i++) { + int from = logs[i][0]; + int to = logs[i][1]; + int weight = logs[i][2]; + + adjMatrix[from][to] = adjMatrix[to][from] = 0; + + // Ʈ ϱ + int diameter1 = getDiameter(from); + int diameter2 = getDiameter(to); + // max + max = Math.max(max, diameter1 + diameter2 + weight); + + adjMatrix[from][to] = adjMatrix[to][from] = weight; + } + + + System.out.println(max); + + } + + static int farthestNode; + static int longestPathLen; + static boolean[] visited; + + private static int getDiameter(int node) { + farthestNode = node; + longestPathLen = 0; + + visited = new boolean[N]; + + // dfs հŸ ִ ϱ + dfs(node, 0); + + longestPathLen = 0; + visited = new boolean[N]; + // dfs հŸ ϱ + dfs(farthestNode, 0); + + return longestPathLen; + } + + private static void dfs(int node, int len) { + + visited[node] = true; + + if(len>longestPathLen) { + longestPathLen = len; + farthestNode = node; + } + + for (int i = 0; i < adjMatrix.length; i++) { + if(!visited[i] && adjMatrix[node][i]>0) { + dfs(i, len + adjMatrix[node][i]); + } + } + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week28/BJ_1890_\354\240\220\355\224\204.java" "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_1890_\354\240\220\355\224\204.java" new file mode 100644 index 0000000..7cc492c --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week28/BJ_1890_\354\240\220\355\224\204.java" @@ -0,0 +1,67 @@ +package week28; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/1890 + * + * Ǯ: + * dp[i][j] i+1 j+1 ϴ + * Ʒ ʿ ̸鼭 dp ̿Ͽ ̵ϴ Ʒ + * ̵ϴ dp table + * + * + * ð⵵: + * O(N^2) + * + * Ǯ̿ ɸ ð: + * 1h + * + */ +public class BJ_1890_ { + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(in.readLine()); + int[][] board = new int[N][N]; + long[][] dp = new long[N][N]; + + StringTokenizer st; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(in.readLine()); + for (int j = 0; j < N; j++) { + board[i][j] = Integer.parseInt(st.nextToken()); + } + } + + // ʱȭ + dp[0][0] = 1; + + for (int row = 0; row < N; row++) { + for (int col = 0; col < N; col++) { + + if(board[row][col]==0) { + continue; + } + + // ̵ + if(col+board[row][col] cloud; // ġ + static Set temp; // ־ ġ + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(in.readLine()); + N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + + A = new int[N][N]; + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(in.readLine()); + for (int j = 0; j < N; j++) { + A[i][j] = Integer.parseInt(st.nextToken()); + } + } + + // ٶ + cloud = new LinkedList<>(); + temp = new HashSet<>(); + cloud.add(new int[] {N-1, 0}); + cloud.add(new int[] {N-1, 1}); + cloud.add(new int[] {N-2, 0}); + cloud.add(new int[] {N-2, 1}); + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(in.readLine()); + int d = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + + moveCloud(d,s, cloud.size()); + makeItRain(); + duplicateWater(); + cloud = new LinkedList<>(); // + makeCloud(); + } + + int ans = accumulateWater(); + System.out.println(ans); + } + + private static int accumulateWater() { + int sum = 0; + for (int i = 0; i < A.length; i++) { + for (int j = 0; j < A.length; j++) { + sum +=A[i][j]; + } + } + return sum; + } + + private static void makeCloud() { + + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + + // ĭ Ȯ + if(temp.contains(i*N+j)) { + continue; + } + + // Ǿ 2 ̸̻ Ǿ + if(A[i][j]>=2) { + cloud.add(new int[] {i,j}); + A[i][j] -=2; + } + } + } + + temp = new HashSet<>(); // ־ ġ + } + + private static void duplicateWater() { + for (int[] position : cloud) { + int row = position[0]; + int col = position[1]; + + for (int d = 2; d < 9; d+=2) { + + int nextRow = row + delta[0][d]; + int nextCol = col + delta[1][d]; + + if(isValid(nextRow, nextCol) && A[nextRow][nextCol]>0) { + A[row][col]++; + } + } + } + } + + + private static boolean isValid(int nextRow, int nextCol) { + return nextRow>=0 && nextCol>=0 && nextRow=N) { + nextRow %= N; + }else if(nextRow<0) { + nextRow += N; + } + int nextCol = col + (s*delta[1][d]%N); + if(nextCol>=N) { + nextCol %= N; + }else if(nextCol<0) { + nextCol += N; + } + + cloud.add(new int[] {nextRow, nextCol}); + temp.add(nextRow*N+nextCol); + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1654_\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1654_\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.java" new file mode 100644 index 0000000..6a322d3 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1654_\353\236\234\354\204\240\354\236\220\353\245\264\352\270\260.java" @@ -0,0 +1,61 @@ +package week29; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : ڸ + * ũ: https://www.acmicpc.net/problem/1654 + * + * Ǯ: + * upper bound + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_1654_ڸ { + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + int K = Integer.parseInt(st.nextToken()); + int N = Integer.parseInt(st.nextToken()); + + int[] len = new int[K]; + long max = -1; + for (int i = 0; i < K; i++) { + len[i] = Integer.parseInt(in.readLine()); + max = Math.max(max, len[i]); + } + + long left=0, right=max+1, mid = 0; // upper bound ؾϹǷ max ϴ ϶ max + 1 right + + while(left=N) { // N ų ø + left = mid+1; + }else { // N ̱ + right = mid; + } + } + + System.out.println(left-1); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1725_\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.java" "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1725_\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.java" new file mode 100644 index 0000000..3df7166 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_1725_\355\236\210\354\212\244\355\206\240\352\267\270\353\236\250.java" @@ -0,0 +1,93 @@ +package week29; + +import java.util.Scanner; + +/** + * : ׷ + * ũ: https://www.acmicpc.net/problem/1725 + * + * Ǯ: + * + * ݾ Ͽ ׸Ʈ ִ ū 簢 + * ʿ ū ϴ ϴ ū 簢 ̸ Ͽ + * ū + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ + +public class BJ_1725_׷ { + + static int[] histogram; + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + + histogram = new int[N]; + + for (int i = 0; i < N; i++) { + histogram[i] = sc.nextInt(); + } + + int ans = getMaxRectangleArea(0,N-1); + + System.out.println(ans); + } + + private static int getMaxRectangleArea(int from, int to) { + + if(from==to) { + return histogram[from]; + } + + int left = (from+to)/2; + int right = left; + + // κ ִ 簢 + int leftMaxRectangleArea = getMaxRectangleArea(from, left); + + // κ ִ 簢 + int rightMaxRectangleArea = getMaxRectangleArea(right+1, to); + + // ġ κ ϴ ִ 簢 + int maxArea = histogram[right]; + int height = histogram[right]; + + while(left>from && righthistogram[right+1]) { + left--; + height = Math.min(height, histogram[left]); + + }else { + right++; + height = Math.min(height, histogram[right]); + } + + maxArea = Math.max(maxArea, (right-left+1) * height); + + } + + while(rightfrom) { + left--; + height = Math.min(height, histogram[left]); + maxArea = Math.max(maxArea, (right-left+1) * height); + } + + return Math.max(Math.max(leftMaxRectangleArea, rightMaxRectangleArea), maxArea); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week29/BJ_20056_\353\247\210\353\262\225\354\202\254\354\203\201\354\226\264\354\231\200\355\214\214\354\235\264\354\226\264\353\263\274.java" "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_20056_\353\247\210\353\262\225\354\202\254\354\203\201\354\226\264\354\231\200\355\214\214\354\235\264\354\226\264\353\263\274.java" new file mode 100644 index 0000000..122b098 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_20056_\353\247\210\353\262\225\354\202\254\354\203\201\354\226\264\354\231\200\355\214\214\354\235\264\354\226\264\353\263\274.java" @@ -0,0 +1,186 @@ +package week29; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.StringTokenizer; + + +/** + * : ̾ + * ũ: + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_20056_̾ { + + static class Fireball{ + int r,c,m,s,d; + + public Fireball(int r, int c, int m, int s, int d) { + super(); + this.r = r; + this.c = c; + this.m = m; + this.s = s; + this.d = d; + + if(map[current][r][c]==null) { + map[current][r][c] = new LinkedList<>(); + } + + map[current][r][c].add(this); + } + + void move() { + r += delta[0][d]*s; + if(r>=N) { + r %= N; + }else if(r<0) { + r = (r%N)+N; + r = r==N?0:r; + } + c += delta[1][d]*s; + if(c>=N) { + c %= N; + }else if(c<0) { + c = (c%N)+N; + c = c==N?0:c; + } + + if(map[next][r][c]==null) { + map[next][r][c] = new LinkedList<>(); + } + + map[next][r][c].add(this); + + } + } + + + static int[][] delta = {{-1,-1,0,1,1,1,0,-1},{0,1,1,1,0,-1,-1,-1}}; + static List[][][] map; + static int current = 0, next = 1, N; + static int[][] newDirection = {{0,2,4,6},{1,3,5,7}}; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + + map = new List[2][N][N]; + + Queue queue = new LinkedList<>(); + + for (int i = 0; i < M; i++) { + + st = new StringTokenizer(in.readLine()); + int r = Integer.parseInt(st.nextToken())-1; + int c = Integer.parseInt(st.nextToken())-1; + int m = Integer.parseInt(st.nextToken()); + int s = Integer.parseInt(st.nextToken()); + int d = Integer.parseInt(st.nextToken()); + + Fireball fireball = new Fireball(r,c,m,s,d); + queue.add(fireball); + + } + + printMap(); + + // ̵ + for (int i = 0; i < K; i++) { + // ̾ ڽ d ӷ sĭ ŭ ̵ + while(!queue.isEmpty()) { + Fireball fireball = queue.poll(); + fireball.move(); + } + + next = next^1; + current = current^1; + map[next] = new List[N][N]; + + // ĭ ִ ̾ ϳ + for (int j = 0; j < N; j++) { + for (int k = 0; k < N; k++) { + if(map[current][j][k]!=null) { + + if(map[current][j][k].size()==1) { + queue.add(map[current][j][k].get(0)); + continue; + } + + int mSum = 0, sSum = 0; + boolean isEven = false, isOdd = false; + int numberOfFireball = map[current][j][k].size(); + + for (Fireball fireball : map[current][j][k]) { + mSum += fireball.m; + sSum += fireball.s; + if(fireball.d%2==0) { + isEven = true; + }else { + isOdd = true; + } + } + + // 0 ΰ ŵ + if(mSum/5==0) { + continue; + } + + int dir = isEven&&isOdd?1:0; + + for (int l = 0; l < 4; l++) { + Fireball fireball = new Fireball(j, k, mSum/5, sSum/numberOfFireball, newDirection[dir][l]); + queue.add(fireball); + } + + } + } + } + + next = next^1; + current = current^1; + map[next] = new List[N][N]; + } + printMap(); + int mSum = 0; + for (Fireball fireball : queue) { + mSum += fireball.m; + } + + System.out.println(mSum); + } + + private static void printMap() { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + if(map[current][i][j]!=null) { + System.out.print(" "); + }else { + System.out.print(" "); + } + } + System.out.println(); + } + System.out.println(); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week29/BJ_2206_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_2206_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\260.java" new file mode 100644 index 0000000..3bf10f0 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week29/BJ_2206_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\260.java" @@ -0,0 +1,116 @@ +package week29; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +/** + * : μ ̵ϱ ũ: https://www.acmicpc.net/problem/2206 + * + * Ǯ: + * bfs Ž + * visited迭 ϳ μ ¿ μ ΰ + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * 30m + * + */ +public class BJ_2206_μ̵ϱ { + + static int[][] map; + static final int TRUE = 0; + static final int FALSE = 1; + static int N, M; + static int[][] delta = { { 0, 0, -1, 1 }, { -1, 1, 0, 0 } }; + static boolean[][][] visited; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + + map = new int[N][M]; + + for (int i = 0; i < N; i++) { + String[] split = in.readLine().split(""); + for (int j = 0; j < M; j++) { + map[i][j] = Integer.parseInt(split[j]); + } + } + + visited = new boolean[2][N][M]; + + int ans = bfs(); + + System.out.println(ans); + } + + private static int bfs() { + + Queue queue = new LinkedList<>(); + + queue.add(new int[] { 0, 0, 0 }); + visited[0][0][0] = true; + + int cnt = 1; + + while (!queue.isEmpty()) { + + int size = queue.size(); + + while (size-- > 0) { + int[] position = queue.poll(); + + int row = position[0]; + int col = position[1]; + int canBreak = position[2]; + + if (row == N - 1 && col == M - 1) { + return cnt; + } + + for (int d = 0; d < 4; d++) { + int newRow = row + delta[0][d]; + int newCol = col + delta[1][d]; + + if (isValid(newRow, newCol, canBreak)) { + + if (canBreak == TRUE) { // Ⱥμ + if (map[newRow][newCol] == 1) { + visited[1][newRow][newCol] = true; + queue.add(new int[] { newRow, newCol, FALSE }); + } else { + visited[0][newRow][newCol] = true; + queue.add(new int[] { newRow, newCol, TRUE }); + } + } else if (canBreak == FALSE && map[newRow][newCol] == 0) { // ν + visited[1][newRow][newCol] = true; + queue.add(new int[] { newRow, newCol, FALSE }); + } + + } + } + } + cnt++; + + } + + return -1; + } + + private static boolean isValid(int newRow, int newCol, int canBreak) { + return newRow >= 0 && newCol >= 0 && newRow < N && newCol < M && !visited[canBreak][newRow][newCol]; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week30/BJ_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.java" "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.java" new file mode 100644 index 0000000..dc0bb62 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_14889_\354\212\244\355\203\200\355\212\270\354\231\200\353\247\201\355\201\254.java" @@ -0,0 +1,98 @@ +package week30; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : ŸƮ ũ + * ũ: https://www.acmicpc.net/problem/14889 + * + * Ǯ: + * 1. + * Ѹ ΰ N-1_C_N ϱ + * 2. ɷġ ϱ + * + * ð⵵: + * + * Ǯ̿ ɸ ð: + * 50m + * + */ +public class BJ_14889_ŸƮ͸ũ { + + static int[][] S; + static int N; + static int[][] teams; + static boolean[] isTeam0; + static int min = Integer.MAX_VALUE; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + S = new int[N][N]; + teams = new int[2][N/2]; + isTeam0 = new boolean[N]; + StringTokenizer st; + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(in.readLine()); + for (int j = 0; j < N; j++) { + S[i][j] = Integer.parseInt(st.nextToken()); + } + } + + combination(0,0); + + System.out.println(min); + } + + private static void combination(int start, int depth) { + + if(depth==N/2) { + + int idx = 0; + + for (int i = 0; i < N-1; i++) { + if(!isTeam0[i]) { + teams[1][idx++] = i; + } + } + + teams[1][N/2-1] = N-1; + + int team0 = 0; + int team1 = 0; + + // ɷġ + for (int i = 0; i < N/2-1; i++) { + for (int j = i+1; j < N/2; j++) { + + int start1 = teams[0][i]; + int start2 = teams[0][j]; + int link1 = teams[1][i]; + int link2 = teams[1][j]; + + team0 += (S[start1][start2] + S[start2][start1]); + team1 += (S[link1][link2] + S[link2][link1]); + + } + } + + min = Math.min(min, Math.abs(team0-team1)); + + return; + } + + for (int i = start; i < N-1; i++) { + teams[0][depth] = i; + isTeam0[i] = true; + combination(i+1, depth+1); + isTeam0[i] = false; + } + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16235_\353\202\230\353\254\264\354\236\254\355\205\214\355\201\254.java" "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16235_\353\202\230\353\254\264\354\236\254\355\205\214\355\201\254.java" new file mode 100644 index 0000000..e682c38 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16235_\353\202\230\353\254\264\354\236\254\355\205\214\355\201\254.java" @@ -0,0 +1,168 @@ +package week30; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.StringTokenizer; + +/** + * : ũ ũ: https://www.acmicpc.net/problem/16235 + * + * Ǯ: + * ̼ Ͽ ֱ + * ĭ ʿ + * + * + * ð⵵: + * O(?) + * + * Ǯ̿ ɸ ð: + * 2h + * + */ +public class BJ_16235_ũ { + + static class Tree implements Comparable { + int r, c, age; + + public Tree(int r, int c, int age) { + super(); + this.r = r; + this.c = c; + this.age = age; + } + + @Override + public int compareTo(Tree o) { + return this.age - o.age; + } + + } + + static int[][] ground, A; + static List trees; + static Queue deadTrees, breedingTrees; + static int N, treeCnt; + static int[][] delta = { { 0, 0, -1, 1, -1, 1, -1, 1 }, { -1, 1, 0, 0, -1, 1, 1, -1 } }; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + + N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + + treeCnt = 0; + A = new int[N][N]; + ground = new int[N][N]; + deadTrees = new LinkedList<>(); + breedingTrees = new LinkedList<>(); + trees = new LinkedList<>(); + + for (int i = 0; i < N; i++) { + st = new StringTokenizer(in.readLine()); + for (int j = 0; j < N; j++) { + ground[i][j] = 5; + A[i][j] = Integer.parseInt(st.nextToken()); + } + } + + for (int i = 0; i < M; i++) { + st = new StringTokenizer(in.readLine()); + int x = Integer.parseInt(st.nextToken()) - 1; + int y = Integer.parseInt(st.nextToken()) - 1; + int z = Integer.parseInt(st.nextToken()); + + trees.add(new Tree(x, y, z)); + treeCnt++; + } + + for (int year = 0; year < K; year++) { + spring(); + summer(); + fall(); + winter(); + } + + System.out.println(treeCnt); + + } + + private static void winter() { + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + ground[i][j] += A[i][j]; + } + } + } + + private static void fall() { + + while (!breedingTrees.isEmpty()) { + Tree tree = breedingTrees.poll(); + for (int d = 0; d < 8; d++) { + int newRow = tree.r + delta[0][d]; + int newCol = tree.c + delta[1][d]; + + if (isValid(newRow, newCol)) { + trees.add(new Tree(newRow, newCol, 1)); + treeCnt++; + } + } + } + + } + + private static boolean isValid(int newRow, int newCol) { + return newRow >= 0 && newCol >= 0 && newRow < N && newCol < N; + } + + private static void summer() { + + // ߰ + while (!deadTrees.isEmpty()) { + Tree deadTree = deadTrees.poll(); + ground[deadTree.r][deadTree.c] += deadTree.age / 2; + } + + } + + private static void spring() { + + // + Collections.sort(trees); + + // ͷ + Iterator it = trees.iterator(); + + while (it.hasNext()) { + Tree tree = it.next(); + + // + if (ground[tree.r][tree.c] < tree.age) { + deadTrees.add(tree); + it.remove(); + treeCnt--; + continue; + } + + // + ground[tree.r][tree.c] -= tree.age; + tree.age++; + + // İ ť ߰ + if (tree.age % 5 == 0) { + breedingTrees.add(tree); + } + } + + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16946_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\2604.java" "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16946_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\2604.java" new file mode 100644 index 0000000..ed34f21 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week30/BJ_16946_\353\262\275\353\266\200\354\210\230\352\263\240\354\235\264\353\217\231\355\225\230\352\270\2604.java" @@ -0,0 +1,117 @@ +package week30; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashSet; +import java.util.Set; +import java.util.StringTokenizer; + +/** + * : μ ̵ϱ 4 + * ũ: https://www.acmicpc.net/problem/16946 + * + * Ǯ: + * Ź μ Ž Ž ߺϿ ȿ + * ̸ Žؼ иϰ ðȿ ̵ + * ĭ + * + * ð⵵: + * O(N^2) + * + * Ǯ̿ ɸ ð: + * 30m + * + */ +public class BJ_16946_μ̵ϱ4 { + + static int[][] map, emptySpaceRecord; + static int emptyIdCnt,N,M; + static int[] emptySpaceSize; + static int[][] delta = {{0,0,1,-1},{1,-1,0,0}}; + static SetcheckSet; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + StringTokenizer st = new StringTokenizer(in.readLine()); + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + + map = new int[N][M]; + emptySpaceRecord = new int[N][M]; + emptySpaceSize = new int[1000000]; + + for (int i = 0; i < N; i++) { + String line = in.readLine(); + for (int j = 0; j < M; j++) { + map[i][j] = line.charAt(j)-'0'; + } + } + + // ̸ ׷ȭ + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + // ̰ Ž dfs Ž + if(map[i][j]==0 && emptySpaceRecord[i][j]==0) { + dfs(i,j,++emptyIdCnt); + } + } + } + + // ̵ ġ ϱ + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + if(map[i][j]==0) { + sb.append(0); + }else { + checkSet = new HashSet<>(); // Ʈ + int sum = 1; + for (int d = 0; d < 4; d++) { + int newRow = i + delta[0][d]; + int newCol = j + delta[1][d]; + + if(isValid2(newRow, newCol)) { + checkSet.add(emptySpaceRecord[newRow][newCol]); // id + sum += emptySpaceSize[emptySpaceRecord[newRow][newCol]]; // ũ ϱ + } + } + sb.append(sum%10); + } + } + sb.append("\n"); + } + + System.out.println(sb.toString()); + } + + private static boolean isValid2(int newRow, int newCol) { + // ȿ ְ ̹ Ȯ ƴ ̸ true + return newRow>=0 && newCol>=0 && newRow=0 && newCol>=0 && newRow queue = new LinkedList<>(); + visited = new boolean[h][w]; + + queue.add(currentPosition); + visited[currentPosition[0]][currentPosition[1]] = true; + + int cnt = 0; + int dirtCnt = 0; + + while(!queue.isEmpty()) { + int size = queue.size(); + + while(size-->0) { + int[] position = queue.poll(); + int row = position[0]; + int col = position[1]; + + if(map[row][col]=='*') { + distanceFromStart[dirtyPlacesMap[row*w+col]] = cnt; + dirtCnt++; + } + + for (int d = 0; d < 4; d++) { + int newRow = position[0] + delta[0][d]; + int newCol = position[1] + delta[1][d]; + + if(isValid(newRow, newCol)) { + visited[newRow][newCol] = true; + queue.add(new int[] {newRow, newCol}); + } + } + } + cnt++; + } + + if(dirtCnt!=dirtyPlacesCnt) { + return false; + } + + return true; + } + + // ĭ Ÿ ϱ + private static boolean calcAllDistances() { + + for (int i = 0; i < dirtyPlacesCnt; i++) { + + int[] currentPosition = dirtyPlaces[i]; + + Queue queue = new LinkedList<>(); + visited = new boolean[h][w]; + + queue.add(currentPosition); + visited[currentPosition[0]][currentPosition[1]] = true; + + int cnt = 0; + int dirtCnt = 0; + + while(!queue.isEmpty()) { + int size = queue.size(); + + while(size-->0) { + int[] position = queue.poll(); + int row = position[0]; + int col = position[1]; + + if(map[row][col]=='*') { + distances[i][dirtyPlacesMap[row*w+col]] = distances[dirtyPlacesMap[row*w+col]][i] = cnt; + dirtCnt++; + } + + for (int d = 0; d < 4; d++) { + int newRow = position[0] + delta[0][d]; + int newCol = position[1] + delta[1][d]; + + if(isValid(newRow, newCol)) { + visited[newRow][newCol] = true; + queue.add(new int[] {newRow, newCol}); + } + } + } + cnt++; + } + + if(dirtCnt!=dirtyPlacesCnt) { + return false; + } + } + + return true; + } + + private static void permutation(int depth, int[] currentPosition, int distanceAcc) { + + if(depth==dirtyPlacesCnt) { + min = Math.min(min, distanceAcc); + return; + } + + for (int i = 0; i < dirtyPlacesCnt; i++) { + if(used[i]) { + continue; + } + used[i] = true; + + // ǥ µ ʿ ̵Ÿ ϱ + int requiredMoves; + if (depth==0) { + requiredMoves = distanceFromStart[i]; + }else { + int currentPositionID = dirtyPlacesMap[currentPosition[0]*w+currentPosition[1]]; + requiredMoves = distances[currentPositionID][i]; + } + + permutation(depth+1, dirtyPlaces[i], distanceAcc + requiredMoves); + used[i] = false; + } + } + + private static boolean isValid(int newRow, int newCol) { + return newRow>=0 && newCol>=0 && newRow=0 && newCol>=0 && newRow<5 && newCol<5 && !visited[newRow][newCol] && (map[room][newRow][newCol]=='P' || map[room][newRow][newCol]=='O'); + } +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week31/BJ_1007_\353\262\241\355\204\260\353\247\244\354\271\255.java" "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_1007_\353\262\241\355\204\260\353\247\244\354\271\255.java" new file mode 100644 index 0000000..229d263 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_1007_\353\262\241\355\204\260\353\247\244\354\271\255.java" @@ -0,0 +1,84 @@ +package week31; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : ͸Ī + * ũ: https://www.acmicpc.net/problem/1007 + * + * Ǯ: + * SUM(vectors) = SUM( ) - SUM( ) + * з ջ + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * 2h + * + */ +public class BJ_1007_͸Ī { + + static boolean[] visited; + static int N; + static double min; + static int[][] dots; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int T = Integer.parseInt(in.readLine()); + + for (int testCase = 0; testCase < T; testCase++) { + + N = Integer.parseInt(in.readLine()); + dots = new int[N][2]; + min = Double.MAX_VALUE; + visited = new boolean[N]; + + for (int i = 0; i < N; i++) { + StringTokenizer st = new StringTokenizer(in.readLine()); + dots[i][0] = Integer.parseInt(st.nextToken()); + dots[i][1] = Integer.parseInt(st.nextToken()); + } + + combination(0,0); + System.out.println(min); + + } + } + + private static void combination(int depth, int start) { + if(depth==N/2) { + int[] vectorSum = {0,0}; + for (int i = 0; i < N; i++) { + if(visited[i]) { + vectorSum[0] += dots[i][0]; + vectorSum[1] += dots[i][1]; + }else { + vectorSum[0] -= dots[i][0]; + vectorSum[1] -= dots[i][1]; + } + } + + min = Math.min(min, Math.sqrt(Math.pow(vectorSum[0],2) + Math.pow(vectorSum[1], 2))); + return; + } + + for (int i = start; i < N; i++) { + if(visited[i]) { + continue; + } + visited[i] = true; + combination(depth+1, i+1); + visited[i] = false; + } + } + + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week31/BJ_11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.java" "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.java" new file mode 100644 index 0000000..2ab5111 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_11049_\355\226\211\353\240\254\352\263\261\354\205\210\354\210\234\354\204\234.java" @@ -0,0 +1,53 @@ +package week31; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/11049 + * + * Ǯ: + * dp[i][j] : i~j ּڰ + * dp[i][j] = dp[i][k] + dp[k+1][j] + (i row) * (k+1 row) * (j col) + * + * ð⵵: + * O(N^3) + * + * Ǯ̿ ɸ ð: + * 2h + * + */ +public class BJ_11049_İ { + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(in.readLine()); + int[][] matrix = new int[N][2]; + int[][] dp = new int[N][N]; + + for (int i = 0; i < N; i++) { + StringTokenizer st = new StringTokenizer(in.readLine()); + matrix[i] = new int[] {Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; + } + + for (int i = 1; i < N; i++) { + for (int j = 0; j < N-i; j++) { + int min = Integer.MAX_VALUE; + for (int k = 0; k < i; k++) { + min = Math.min(min, dp[j][j+k] + dp[j+k+1][j+i] + matrix[j][0] * matrix[j+k+1][0] * matrix[j+i][1]); + } + dp[j][j+i] = min; + } + } + + + System.out.println(dp[0][N-1]); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week31/BJ_14888_\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_14888_\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.java" new file mode 100644 index 0000000..f824a2c --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_14888_\354\227\260\354\202\260\354\236\220\353\201\274\354\233\214\353\204\243\352\270\260.java" @@ -0,0 +1,95 @@ +package week31; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : ֱ + * ũ: https://www.acmicpc.net/problem/14888 + * + * Ǯ: + * ߺ(?) + * + * + * ð⵵: + * O(N!) + * + * Ǯ̿ ɸ ð: + * 30m + * + */ +public class BJ_14888_ڳֱ { + + static final char[] operator = {'+','-','*','/'}; + static int[] operatorCnt = {0,0,0,0}; + static int[] A; + static char[] opertorSequence; + static int N, max = Integer.MIN_VALUE, min=Integer.MAX_VALUE; + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + N = Integer.parseInt(in.readLine()); + A = new int[N]; + opertorSequence = new char[N-1]; + + StringTokenizer st = new StringTokenizer(in.readLine()); + for (int i = 0; i < N; i++) { + A[i] = Integer.parseInt(st.nextToken()); + } + + st = new StringTokenizer(in.readLine()); + for (int i = 0; i < 4; i++) { + operatorCnt[i] = Integer.parseInt(st.nextToken()); + } + + permutation(0); + + System.out.println(max); + System.out.println(min); + } + + private static void permutation(int depth) { + if(depth==N-1) { + int result = runOperation(); + min = Math.min(min, result); + max = Math.max(max, result); + return; + } + for (int i = 0; i < 4; i++) { + if(operatorCnt[i]!=0) { + opertorSequence[depth] = operator[i]; + operatorCnt[i]--; + permutation(depth+1); + operatorCnt[i]++; + } + } + } + + private static int runOperation() { + + int result = A[0]; + + for (int i = 1; i < N; i++) { + switch(opertorSequence[i-1]) { + case '+': + result += A[i]; + break; + case '-': + result -= A[i]; + break; + case '*': + result *= A[i]; + break; + case '/': + result /= A[i]; + break; + } + } + + return result; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week31/BJ_15685_\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.java" "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_15685_\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.java" new file mode 100644 index 0000000..9ce817c --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_15685_\353\223\234\353\236\230\352\263\244\354\273\244\353\270\214.java" @@ -0,0 +1,74 @@ +package week31; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : 巡 Ŀ + * ũ: https://www.acmicpc.net/problem/15685 + * + * Ǯ: + * ̴ ϰ 밡 Ѿ Ųٷ 󰡸 ٲ ̵ϸ + * ǥ + * + * ð⵵: + * O(20 * 1024 + 10000 * 4) + * + * Ǯ̿ ɸ ð: + * 1h + * + */ +public class BJ_15685_巡Ŀ { + static boolean[][] map = new boolean[101][101]; + static int[][] delta = {{0,-1,0,1},{1,0,-1,0}}; + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + int N = Integer.parseInt(in.readLine()); + + for (int i = 0; i < N; i++) { + StringTokenizer st = new StringTokenizer(in.readLine()); + makeDragonCurve(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())); + } + int cnt = 0; + + for (int i = 0; i < 100; i++) { + for (int j = 0; j < 100; j++) { + if(map[i][j] && map[i+1][j] && map[i][j+1] && map[i+1][j+1]) { + cnt++; + } + } + } + + System.out.println(cnt); + } + + private static void makeDragonCurve(int x, int y, int d, int g) { + int[] dragonCurveHistory = new int[1024]; + int curveIdx = 0; + + map[y][x] = true; + y += delta[0][d]; + x += delta[1][d]; + + dragonCurveHistory[curveIdx++] = d; + map[y][x] = true; + + + for (int generation = 0; generation < g; generation++) { + // Ŀ긦 ׸ + for (int i = curveIdx-1; i >= 0; i--) { + int dir = (dragonCurveHistory[i] + 1) % 4; + dragonCurveHistory[curveIdx++] = dir; + y += delta[0][dir]; + x += delta[1][dir]; + map[y][x] = true; + } + } + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week31/BJ_2580_\354\212\244\353\217\204\354\277\240.java" "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_2580_\354\212\244\353\217\204\354\277\240.java" new file mode 100644 index 0000000..5a281e0 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week31/BJ_2580_\354\212\244\353\217\204\354\277\240.java" @@ -0,0 +1,89 @@ +package week31; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/2580 + * + * Ǯ: + * ׸ 9 3*3 簢 ִ ڵ boolean 迭 ǥصΰ + * dfs ĭ 1~9 ڸ ϳ ־鼭 ǿ ĭ ä. + * + * + * ð⵵: + * ? + * + * Ǯ̿ ɸ ð: + * 15m + * + */ +public class BJ_2580_ { + + static int[][] sdoku = new int[9][9]; + static int[][] blankPositions = new int[81][]; + static int numberOfBlanks = 0; + static boolean[][] rowCheck = new boolean[9][10]; + static boolean[][] colCheck = new boolean[9][10]; + static boolean[][][] squareCheck = new boolean[3][3][10]; + + public static void main(String[] args) throws IOException { + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + + for (int i = 0; i < 9; i++) { + StringTokenizer st = new StringTokenizer(in.readLine()); + for (int j = 0; j < 9; j++) { + int input = Integer.parseInt(st.nextToken()); + sdoku[i][j] = input; + if(input==0) { + blankPositions[numberOfBlanks++] = new int[] {i,j}; + } + rowCheck[i][input] = true; + colCheck[j][input] = true; + squareCheck[i/3][j/3][input] = true; + } + } + + dfs(0); + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 9; j++) { + sb.append(sdoku[i][j] + " "); + } + sb.append("\n"); + } + + System.out.println(sb.toString()); + } + + + private static boolean dfs(int depth) { + + if(depth==numberOfBlanks) { + return true; + } + + int[] blankPosition = blankPositions[depth]; + int row = blankPosition[0]; + int col = blankPosition[1]; + + for (int i = 1; i <= 9; i++) { + if(!rowCheck[row][i] && !colCheck[col][i] && !squareCheck[row/3][col/3][i]) { + sdoku[row][col] = i; + rowCheck[row][i] = colCheck[col][i] = squareCheck[row/3][col/3][i] = true; + if(dfs(depth+1)) { + return true; + } + rowCheck[row][i] = colCheck[col][i] = squareCheck[row/3][col/3][i] = false; + } + } + + return false; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week33/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week33/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" new file mode 100644 index 0000000..bc83a98 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week33/BJ_14499_\354\243\274\354\202\254\354\234\204\352\265\264\353\246\254\352\270\260.java" @@ -0,0 +1,137 @@ +package week33; + +import java.util.Scanner; + +/** + * :ֻ + * ũ:https://www.acmicpc.net/problem/14499 + * + * : + * + * + * ð⵵: + * + * + * ҿ ð: + * + */ +public class BJ_14499_ֻ { + static class Dice{ + int top, bottom, east, west, north, south; + + public Dice(int top, int bottom, int east, int west, int north, int south) { + super(); + this.top = top; + this.bottom = bottom; + this.east = east; + this.west = west; + this.north = north; + this.south = south; + } + + public void rollDown(){ + int temp = this.bottom; + this.bottom = this.south; + this.south = this.top; + this.top = this.north; + this.north = temp; + } + + public void rollUp(){ + int temp = this.north; + this.north = this.top; + this.top = this.south; + this.south = this.bottom; + this.bottom = temp; + } + + public void rollLeft(){ + int temp = this.west; + this.west = this.top; + this.top = this.east; + this.east = this.bottom; + this.bottom = temp; + } + + public void rollRight(){ + int temp = this.east; + this.east = this.top; + this.top = this.west; + this.west = this.bottom; + this.bottom = temp; + } + + public void roll(int direction) { + switch(direction) { + case 1: + this.rollRight(); + break; + case 2: + this.rollLeft(); + break; + case 3: + this.rollUp(); + break; + case 4: + this.rollDown(); + break; + } + } + + public int mark(int numberOnBoard) { + if(numberOnBoard==0) { + return this.bottom; + }else { + this.bottom = numberOnBoard; + return 0; + } + } + + @Override + public String toString() { + return "Dice [top=" + top + ", bottom=" + bottom + ", east=" + east + ", west=" + west + ", north=" + north + + ", south=" + south + "]"; + } + + } + + static int[][] delta = {{0,0,0,-1,1},{0,1,-1,0,0}}; + static int N,M; + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + N = sc.nextInt(); + M = sc.nextInt(); + int x = sc.nextInt(); + int y = sc.nextInt(); + int K = sc.nextInt(); + + int[][] board = new int[N][M]; + + for (int i = 0; i < N; i++) { + for (int j = 0; j < M; j++) { + board[i][j] = sc.nextInt(); + } + } + + Dice dice = new Dice(0,0,0,0,0,0); + + for (int i = 0; i < K; i++) { + int input = sc.nextInt(); + + int newX = x + delta[0][input]; + int newY = y + delta[1][input]; + + if(!isValid(newX, newY)) continue; + x = newX; + y = newY; + dice.roll(input); + board[x][y]=dice.mark(board[x][y]); + System.out.println(dice.top); + } + } + private static boolean isValid(int newX, int newY) { + return newX>=0 && newX=0 && newY { + int num, cnt; + + public Number(int num, int cnt) { + super(); + this.num = num; + this.cnt = cnt; + } + + @Override + public int compareTo(Number o) { + return this.cnt == o.cnt ? this.num - o.num : this.cnt - o.cnt; + } + + } + + static int[][] A = new int[100][100]; + static int maxRow = 3, maxCol = 3; + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int r = sc.nextInt(); + int c = sc.nextInt(); + int k = sc.nextInt(); + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + A[i][j] = sc.nextInt(); + } + } + + int time = 0; + while (time <= 100) { + + // A[r][c] üũ + if (A[r - 1][c - 1] == k) { + System.out.println(time); + return; + } + + // + if (maxRow >= maxCol) { // R + operation(maxRow, maxCol, true); + } else { // C + operation(maxCol, maxRow, false); + } + + time++; + } + + System.out.println(-1); + } + + private static void operation(int a, int b, boolean isRowOperation) { + + // ִ / ʱȭ + if (isRowOperation) { + maxCol = 0; + }else { + maxRow = 0; + } + + int[][] temp = new int[100][100]; // + for (int i = 0; i < a; i++) { + + MapcntMap = new HashMap<>(); // īƮ + for (int j = 0; j < b; j++) { + + // īƮ + if (isRowOperation) { + if(A[i][j]==0) continue; + Number number = cntMap.getOrDefault(A[i][j], new Number(A[i][j], 0)); + number.cnt++; + cntMap.put(A[i][j], number); + } else { + if(A[j][i]==0) continue; + Number number = cntMap.getOrDefault(A[j][i], new Number(A[j][i], 0)); + number.cnt++; + cntMap.put(A[j][i], number); + } + } + + // Ģ + List numberList = new ArrayList<>(100); + + for (Object val : cntMap.values()) { + numberList.add((Number) val); + } + + Collections.sort(numberList); + int maxIdx = Math.min(50, numberList.size()); + + + // ִ ࿭ + if (isRowOperation) { + maxCol = Math.max(maxCol, maxIdx*2); + }else { + maxRow = Math.max(maxRow, maxIdx*2); + } + + + for (int j = 0; j < maxIdx; j++) { + if (isRowOperation) { + temp[i][j * 2] = numberList.get(j).num; + temp[i][j * 2 + 1] = numberList.get(j).cnt; + } else { + temp[j * 2][i] = numberList.get(j).num; + temp[j * 2 + 1][i] = numberList.get(j).cnt; + } + } + } + A = temp; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week35/BJ_1912_\354\227\260\354\206\215\355\225\251.java" "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_1912_\354\227\260\354\206\215\355\225\251.java" new file mode 100644 index 0000000..721a2fe --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_1912_\354\227\260\354\206\215\355\225\251.java" @@ -0,0 +1,52 @@ +package week35; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/1912 + * + * Ǯ: + * dp + * dp[i] = max(0 i-1° + i° , i° ) + * + * + * ð⵵: + * O(N) + * + * + * Ǯ̿ ɸ ð: + * 30m + * + */ +public class BJ_1912_ { + + public static void main(String[] args) throws NumberFormatException, IOException { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int n = Integer.parseInt(br.readLine()); + + st = new StringTokenizer(br.readLine()); + + int[] dp = new int[n]; + + dp[0] = Integer.parseInt(st.nextToken()); + + int max = dp[0]; + + for (int i = 1; i < n; i++) { + int in = Integer.parseInt(st.nextToken()); + dp[i] = Math.max(in, dp[i-1] + in); + max = Math.max(max, dp[i]); + } + + System.out.println(max); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2470_\353\221\220\354\232\251\354\225\241.java" "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2470_\353\221\220\354\232\251\354\225\241.java" new file mode 100644 index 0000000..fb5d501 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2470_\353\221\220\354\232\251\354\225\241.java" @@ -0,0 +1,74 @@ +package week35; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/2470 + * + * Ǯ: + * + * + * μ ̵ + * ̵ + * + * + * ð⵵: + * O(NlogN) + * + * Ǯ̿ ɸ ð: + * 30m + * + * + */ +public class BJ_2470_ο { + + public static void main(String[] args) throws IOException { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + + int N = Integer.parseInt(br.readLine()); + int[] solutions = new int[N]; + + st = new StringTokenizer(br.readLine()); + + for (int i = 0; i < N; i++) { + solutions[i] = Integer.parseInt(st.nextToken()); + } + + Arrays.parallelSort(solutions); + + int ans1 = -1; + int ans2 = -1; + int minSum = 2000000000; + + int left = 0; + int right = N-1; + int max = 2000000000; + + while(left < right) { + int sum = solutions[left] + solutions[right]; + + // + if(Math.abs(sum) < max) { + ans1 = solutions[left]; + ans2 = solutions[right]; + max = Math.abs(sum); + } + + if(sum > 0) + right--; + else + left++; + } + + System.out.println(ans1 + " " + ans2); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2617_\352\265\254\354\212\254\354\260\276\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2617_\352\265\254\354\212\254\354\260\276\352\270\260.java" new file mode 100644 index 0000000..edb3d5d --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_2617_\352\265\254\354\212\254\354\260\276\352\270\260.java" @@ -0,0 +1,66 @@ +package week35; + +import java.util.Scanner; + +/** + * : ã + * ũ: https://www.acmicpc.net/status?user_id=jslee7420&problem_id=2617&from_mine=1 + * + * Ǯ:÷̵ + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_2617_ã { + + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + int M = sc.nextInt(); + int[][] arr = new int[N + 1][N + 1]; + + for (int i = 0; i < M; i++) { + int heavierMarble = sc.nextInt(); + int lighterMarble = sc.nextInt(); + + arr[heavierMarble][lighterMarble] = 1; + arr[lighterMarble][heavierMarble] = -1; + } + + int ans = 0; + + for (int i = 1; i <= N; i++) { + for (int j = 1; j <= N; j++) { + for (int k = 1; k <= N; k++) { + if (arr[k][i] != 0 && arr[j][i] == arr[i][k]) + arr[j][k] = arr[j][i]; + } + } + } + + int[] heavier = new int[N + 1]; + int[] lighter = new int[N + 1]; + for (int i = 1; i <= N; i++) { + for (int j = 1; j <= N; j++) { + if (arr[i][j] == 1) + heavier[i]++; + if (arr[i][j] == -1) + lighter[i]++; + } + } + + for (int i = 1; i <= N; i++) { + if (heavier[i] > N/2 || lighter[i] > N/2) + ans++; + } + System.out.println(ans); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week35/BJ_7569_\355\206\240\353\247\210\355\206\240.java" "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_7569_\355\206\240\353\247\210\355\206\240.java" new file mode 100644 index 0000000..4ff3ee7 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week35/BJ_7569_\355\206\240\353\247\210\355\206\240.java" @@ -0,0 +1,105 @@ +package week35; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.Queue; +import java.util.StringTokenizer; + +/** + * : 丶 + * ũ: https://www.acmicpc.net/problem/7569 + * + * Ǯ: + * + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_7569_丶 { + + static int[][][] map; + static int N,M,H; + static int greenTomatoCnt; + static int[][] delta = {{-1,1,0,0,0,0},{0,0,-1,1,0,0},{0,0,0,0,-1,1}}; + public static void main(String[] args) throws NumberFormatException, 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()); + + map = new int[H][N][M]; + + for (int i = 0; i < H; i++) { + for (int j = 0; j < N; j++) { + st = new StringTokenizer(br.readLine()); + for (int k = 0; k < M; k++) { + map[i][j][k] = Integer.parseInt(st.nextToken()); + if(map[i][j][k]==0) greenTomatoCnt++; + } + } + } + + int ans = bfs(); + + System.out.println(ans); + + } + + private static int bfs() { + + Queue queue = new LinkedList<>(); + int days = -1; + + // ϴ 丶 ť + for (int i = 0; i < H; i++) { + for (int j = 0; j < N; j++) { + for (int k = 0; k < M; k++) { + if(map[i][j][k]==1) { + queue.add(new int[] {i,j,k}); + } + } + } + } + + while(!queue.isEmpty()) { + + int size = queue.size(); + days++; + while(size-->0) { + + int[] position = queue.poll(); + + for (int d = 0; d < 6; d++) { + + int nH = position[0] + delta[0][d]; + int nR = position[1] + delta[1][d]; + int nC = position[2] + delta[2][d]; + + if(!isValid(nH, nR, nC)) continue; + + // 丶 + map[nH][nR][nC] = 1; + greenTomatoCnt--; + queue.add(new int[] {nH, nR, nC}); + } + } + } + + return greenTomatoCnt==0 ? days : -1; + } + + private static boolean isValid(int nH, int nR, int nC) { + return nH>=0 && nH=0 && nR=0 && nC[] tree; + static int[] numOfSubordinates; + + public static void main(String[] args) throws Exception{ + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int N = Integer.parseInt(br.readLine()); + st = new StringTokenizer(br.readLine()); + tree = new ArrayList[N]; + numOfSubordinates = new int[N]; + + for (int i = 0; i < N; i++) { + tree[i] = new ArrayList<>(); + int parent = Integer.parseInt(st.nextToken()); + if(i==0) continue; + tree[parent].add(i); + } + + System.out.println(dfs(0)); + } + + private static int dfs(int curr) { + int max=0; + + PriorityQueue pq = new PriorityQueue<>((o1, o2) -> o2[1] - o1[1]); + + for (Integer next : tree[curr]) { + numOfSubordinates[next] = dfs(next); + pq.add(new int[]{next,numOfSubordinates[next]}); + } + + + int cnt =0; + while (!pq.isEmpty()){ + int[] node = pq.poll(); + cnt++; + max = Math.max(max,node[1]+cnt); + } + + return max; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week36/BJ_12026_BOJ\352\261\260\353\246\254.java" "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_12026_BOJ\352\261\260\353\246\254.java" new file mode 100644 index 0000000..54a9344 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_12026_BOJ\352\261\260\353\246\254.java" @@ -0,0 +1,42 @@ +package week36; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Scanner; + +public class BJ_12026_BOJŸ { + static final int INF = Integer.MAX_VALUE; + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + + int N = sc.nextInt(); + sc.nextLine(); + String road = sc.nextLine(); + + int[] dp = new int[road.length()]; + + Arrays.fill(dp, INF); + dp[0]=0; + HashMap map = new HashMap<>(); + map.put('B', 0); + map.put('O', 1); + map.put('J', 2); + char[] BOJ = {'B','O','J'}; + int cnt = 0; + int k = 0; + int cost = 0; + boolean jump = false; + for (int i = 1; i < N; i++) { + int j = i; + char target = BOJ[(map.get(road.charAt(i))+2)%3]; + while(j>0) { + if(road.charAt(--j)==target && dp[j]!=INF && dp[i]>dp[j] + (i-j) * (i-j)) { + dp[i] = dp[j] + (i-j) * (i-j); + } + } + } + System.out.println(dp[N-1]==INF?-1:dp[N-1]); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week36/BJ_1946_\354\213\240\354\236\205\354\202\254\354\233\220.java" "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_1946_\354\213\240\354\236\205\354\202\254\354\233\220.java" new file mode 100644 index 0000000..48daa1c --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_1946_\354\213\240\354\236\205\354\202\254\354\233\220.java" @@ -0,0 +1,60 @@ +package week36; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Comparator; +import java.util.StringTokenizer; + +/** + * : + * ũ: + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_1946_Ի { + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + Comparator scoreComparator = new Comparator() { + @Override + public int compare(int[] o1, int[] o2) { + return o1[0]-o2[0]; + } + }; + + int T = Integer.parseInt(br.readLine()); + for (int testCase = 0; testCase < T; testCase++) { + int N = Integer.parseInt(br.readLine()); + int[][] scores = new int[N][]; + for (int i = 0; i < N; i++) { + st = new StringTokenizer(br.readLine()); + scores[i] = new int[] {Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; + } + Arrays.sort(scores, scoreComparator); + + int cutLine = scores[0][1]; + int cnt = 1; + for (int i = 1; i < scores.length; i++) { + if(cutLine>scores[i][1]) { + cutLine = scores[i][1]; + cnt++; + } + } + System.out.println(cnt); + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week36/BJ_5430_AC.java" "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_5430_AC.java" new file mode 100644 index 0000000..d62d1a0 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week36/BJ_5430_AC.java" @@ -0,0 +1,96 @@ +package week36; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.Comparator; +import java.util.StringTokenizer; + +/** + * : + * ũ: + * + * Ǯ: + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_5430_AC { + + public static void main(String[] args) throws NumberFormatException, IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st; + + int T = Integer.parseInt(br.readLine()); + + label: for (int testCase = 0; testCase < T; testCase++) { + String p = br.readLine(); + int N = Integer.parseInt(br.readLine()); + int[] arr = new int[N]; + String input = br.readLine(); + input = input.substring(1, input.length()-1); + st = new StringTokenizer(input, ","); + + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(st.nextToken()); + } + + int frontIdx = 0; + int rearIdx = N-1; + boolean isReversed = false; + + for (int i = 0; i < p.length(); i++) { + char operation = p.charAt(i); + + switch(operation) { + case 'R': + int tmp = frontIdx; + frontIdx = rearIdx; + rearIdx = tmp; + isReversed = isReversed?false:true; + break; + case 'D': + if(isReversed) { + if(frontIdxrearIdx) { + System.out.println("error"); + continue label; + } + frontIdx++; + } + break; + } + } + + StringBuilder sb = new StringBuilder(); + sb.append('['); + if(isReversed) { + for (int i = frontIdx; i >= rearIdx; i--) { + sb.append(arr[i]+","); + } + }else { + for (int i = frontIdx; i <= rearIdx; i++) { + sb.append(arr[i]+","); + } + } + if(sb.charAt(sb.length()-1)==',') { + sb.deleteCharAt(sb.length()-1); + } + sb.append(']'); + System.out.println(sb.toString()); + } + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week36/PG_62048_\353\251\200\354\251\241\355\225\234\354\202\254\352\260\201\355\230\225.java" "b/src/\354\235\264\354\240\225\354\210\230/week36/PG_62048_\353\251\200\354\251\241\355\225\234\354\202\254\352\260\201\355\230\225.java" new file mode 100644 index 0000000..9cda55d --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week36/PG_62048_\353\251\200\354\251\241\355\225\234\354\202\254\352\260\201\355\230\225.java" @@ -0,0 +1,43 @@ +package week36; + +/** + * : 簢 + * ũ: https://programmers.co.kr/learn/courses/30/lessons/62048?language=java + * + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class PG_62048_ѻ簢 { + + public static void main(String[] args) { + System.out.println(solution(8,12)); + } + + static public long solution(int w, int h) { + long answer = (long)w*h - (w + h - gcd(w,h)); + return answer; + } + + private static int gcd(int w, int h) { + + int biggerNum = Math.max(w, h); + int smallerNum = Math.min(w, h); + + while(biggerNum%smallerNum!=0) { + int quotient = biggerNum / smallerNum; + int remainder = biggerNum % smallerNum; + + biggerNum = smallerNum; + smallerNum = remainder; + } + + return smallerNum; + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week37/BJ_18870_\354\242\214\355\221\234\354\225\225\354\266\225.java" "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_18870_\354\242\214\355\221\234\354\225\225\354\266\225.java" new file mode 100644 index 0000000..de0cfb3 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_18870_\354\242\214\355\221\234\354\225\225\354\266\225.java" @@ -0,0 +1,62 @@ +package week37; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * : + * ũ: + * + * Ǯ: + * for ҿ ٸ ҿ ũ 񱳸 ϸ O(N^2)ð + * ðʰ Ͼ ֽϴ. ؾմϴ. X_i>X_j + * ϴ ٸ ǥ Ƿ ߺ Ҹ ָ Ŀ ɸ ð + * Ҽ ֽϴ. ÷ Set ü ڿ ϸ ε + * Һ ֽϴ. ġ binary search մϴ. + * + * ð⵵: + * Ŀ O(NlogN), Setü 鶧 ð ɸ 𸣰ڽϴ. + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_18870_ǥ { + + public static void main(String[] args) throws IOException { + BufferedReader bin = new BufferedReader(new InputStreamReader(System.in)); + StringBuilder sb = new StringBuilder(); + + int N = Integer.parseInt(bin.readLine()); + + int[] coordinates = Arrays.asList(bin.readLine().split(" ")).stream().mapToInt(Integer::parseInt).toArray(); + + Set set = new HashSet<>(Arrays.stream(coordinates).boxed().collect(Collectors.toList())); + + ArrayList list = new ArrayList<>(set); //Set -> ArrayList + + Collections.sort(list); // + + int[] sorted = new int[list.size()]; + + for(int i = 0; i < list.size(); i++) { //ArrayList -> Array + sorted[i] = list.get(i); + } + + for(int coordinate:coordinates) { + sb.append((Arrays.binarySearch(sorted, coordinate)+" ")); + } + + + System.out.println(sb.toString()); + + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2559_\354\210\230\354\227\264.java" "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2559_\354\210\230\354\227\264.java" new file mode 100644 index 0000000..8ca9ed5 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2559_\354\210\230\354\227\264.java" @@ -0,0 +1,53 @@ +package week37; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : + * ũ: https://www.acmicpc.net/problem/2559 + * + * Ǯ: + * + * + * ð⵵:O(N) + * + * + * Ǯ̿ ɸ ð: 20min + * + * + */ +public class BJ_2559_ { + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int K = Integer.parseInt(st.nextToken()); + + int[] arr = new int[N]; + int[] accSum = new int[N-K+1]; + + st = new StringTokenizer(br.readLine()); + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(st.nextToken()); + } + + // ùK + for (int i = 0; i < K; i++) { + accSum[0] += arr[i]; + } + + int max= accSum[0]; + for (int i = K; i < N; i++) { + accSum[i-K+1] += arr[i] + accSum[i-K] - arr[i-K]; + max = Math.max(max, accSum[i-K+1]); + } + + System.out.println(max); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2631_\354\244\204\354\204\270\354\232\260\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2631_\354\244\204\354\204\270\354\232\260\352\270\260.java" new file mode 100644 index 0000000..e681ab8 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2631_\354\244\204\354\204\270\354\232\260\352\270\260.java" @@ -0,0 +1,49 @@ +package week37; + +import java.io.IOException; +import java.util.Scanner; + +/** + * : + * ũ: https://www.acmicpc.net/problem/2631 + * + * Ǯ: + * LIS + * + * + * ð⵵: + * + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_2631_ټ { + + + public static void main(String[] args) throws IOException { + Scanner sc = new Scanner(System.in); + int N = sc.nextInt(); + int[] children = new int[N]; + + for (int i = 0; i < N; i++) { + children[i] = sc.nextInt(); + } + + int[] dp = new int[N]; + dp[0] = 1; + int max = 0; + for (int i = 1; i < dp.length; i++) { + dp[i] = 1; + for (int j = 0; j <= i; j++) { + if(children[j]dp[i]) { + dp[i] = dp[j] +1; + } + max = Math.max(dp[i], max); + } + } + + System.out.println(N-max); + } + +} diff --git "a/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2805_\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.java" "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2805_\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.java" new file mode 100644 index 0000000..07fb507 --- /dev/null +++ "b/src/\354\235\264\354\240\225\354\210\230/week37/BJ_2805_\353\202\230\353\254\264\354\236\220\353\245\264\352\270\260.java" @@ -0,0 +1,62 @@ +package week37; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.StringTokenizer; + +/** + * : ڸ + * ũ: https://www.acmicpc.net/problem/2805 + * + * Ǯ: + * ̺Ž Lower Bound + * + * + * ð⵵: + * O(NlogM) + * + * Ǯ̿ ɸ ð: + * + * + */ +public class BJ_2805_ڸ { + + public static void main(String[] args) throws IOException { + + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + StringTokenizer st = new StringTokenizer(br.readLine()); + + int N = Integer.parseInt(st.nextToken()); + int M = Integer.parseInt(st.nextToken()); + + int[] trees = new int[N]; + st = new StringTokenizer(br.readLine()); + + for (int i = 0; i < N; i++) { + trees[i] = Integer.parseInt(st.nextToken()); + } + + int left = 1, right = 1000000000; + int mid= 0; + + while(leftmid?trees[i]-mid:0; + } + + if(totalLen