[Baekjoon] 1992, 2751

2751. 숫자 정렬 2

import java.util.*;
import java.io.*;
public class Main {
	//2751. 숫자 정렬 2
	public static void main(String[] args) throws NumberFormatException, IOException {
		//Scanner sc = new Scanner(System.in);		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		List<Integer> list = new ArrayList<>();
		
		for (int i = 0; i < N; i++) {
			list.add(Integer.parseInt(br.readLine()));
		}
		
		Collections.sort(list);
		
		StringBuilder sb = new StringBuilder();
		for (int k : list) {
			sb.append(k).append('\n');
		}
		
		System.out.println(sb);
	}
	

}

처음에는 arrays.sort를 썼는데 타임리밋이 걸려서
찾아보니깐 arrays.sort보다는 collections.sort가 훨씬 빠르다네요
앞으로는 유용하게 써먹을 예정..!
근데 그렇게 해도 타임리밋이 걸리길래 string -> stringbuilder로 바꿔주니 통과됐읍니다

1992. 쿼드트리

import java.util.*;
import java.io.*;
public class Main {
	//1992. 쿼드트리
	public static int[][] board;
	public static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws NumberFormatException, IOException {
		//Scanner sc = new Scanner(System.in);		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		
		board = new int[N][N];
		
		for (int i = 0; i < N; i++) {
			String line = br.readLine();
			
			for (int j = 0; j < N; j++) {
				board[i][j] = line.charAt(j) - '0';
			}
		}
		
		helper(0, 0, N);
		System.out.println(sb);
		
	}
	
	
	public static void helper(int y, int x, int n) {
		if (allSame(y, x, n)) {
			sb.append(board[y][x]);
			return;
		}
		
		int nextSize = n / 2;
		
		sb.append('(');
		
		helper(y, x, nextSize);
		helper(y, x + nextSize, nextSize);
		helper(y + nextSize, x, nextSize);
		helper(y + nextSize, x + nextSize, nextSize);
		
		sb.append(')');
	}
	
	public static boolean allSame(int y, int x, int n) {
		int cur = board[y][x];
		for (int i = y; i < y + n; i++) {
			for (int j = x; j < x + n; j++) {
				if (board[i][j] != board[y][x]) {
					return false;
				}
			}
		}
		
		return true;
	}
	

}

재귀를 이용해서 풀이~~
일단 bufferedReader을 이용해서 board를 그려 준 다음에
부분을 나눠서 재귀를 돌리는데 이거를 돌리는 기준이
만약에 그 부위에 있는 모든 숫자가 같다면 하나로 요약 가능하니 allSame이라는 함수로 다 같은지 하나하나 돌려가면서 확인해줌
같다면 하나로 요약해주고
다르다면 사등분해서 괄호를 쳐주고 그 안에도 요약이 되는지 확인하기

좋은 웹페이지 즐겨찾기