23년 7월 19일 [알고리즘 - 분할 정복]

sua·2023년 7월 19일
0

알고리즘 가보자고

목록 보기
58/101

백준 1780번 종이의 개수

문제


나의 풀이

import java.io.*;

public class Main {
    public static boolean same(int[][] a, int x, int y, int n) {
        for (int i=x; i<x+n; i++) {
            for (int j=y; j<y+n; j++) {
                if (a[x][y] != a[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }
    public static void solve(int[][] a, int[] cnt, int x, int y, int n) {
        if (same(a, x, y, n)) {
            cnt[a[x][y]+1] += 1;
            return;
        }
        int m = n/3;
        for (int i=0; i<3; i++) {
            for (int j=0; j<3; j++) {
                solve(a, cnt, x+i*m, y+j*m, m);
            }
        }
    }
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.valueOf(br.readLine());
        int[][] a = new int[n][n];
        int[] cnt = new int[3];
        for (int i=0; i<n; i++) {
            String[] line = br.readLine().split(" ");
            for (int j=0; j<n; j++) {
                a[i][j] = Integer.valueOf(line[j]);
            }
        }
        solve(a, cnt, 0, 0, n);
        for (int i=0; i<3; i++) {
            System.out.println(cnt[i]);
        }
    }
}

(x, y)부터 가로로 n개, 세로로 n개의 종이 개수를 확인하는 함수인 solve() 재귀호출하여 해결한다. 부분 문제를 호출하기 전에 같은 수로 되어있는지를 확인해보고 그렇지 않으면 부분 문제를 호출하도록 구현한다.

결과


인프런 서로 다른 빈도수 만들기

문제

나의 풀이

import java.util.HashMap;
import java.util.HashSet;

public class DifferentFrequency {
    public static int solution(String s) {
        int answer = 0;
        HashMap<Character, Integer> sh = new HashMap<>();
        HashSet<Integer> ch = new HashSet<>();
        for(char x : s.toCharArray()) {
            sh.put(x, sh.getOrDefault(x, 0) + 1);
        }
        for(char key : sh.keySet()) {
            while(ch.contains(sh.get(key))) {
                answer++;
                sh.put(key, sh.get(key) - 1);
            }
            if(sh.get(key) == 0) {
                continue;
            }
            ch.add(sh.get(key));
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(DifferentFrequency.solution("aebbbbc"));
    }
}

결과

profile
가보자고

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

정말 좋은 글 감사합니다!

답글 달기