강의로 돌아가기
kshshkim

의도대로 구현된 알고리즘이면 자바 기준 모든 케이스가 10ms 안쪽으로 해결돼야 맞는 것 같습니다.

10초라서 대충 접근했다가 어떻게 최적화 해보려고 해도 기어이 시간 넘어가길래 결국 포기하고 다시 풀었습니다...

작성중인 코드―Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;

class Solution {
    int[] ryan = new int[11];
    int[] apeach = new int[11];
    int maxDiff = 0;
    ArrayList<int[]> candidRyans = new ArrayList<>();

    void onEnd(int scoreDiff) {
        if (scoreDiff == 0) {
            return;
        }
        if(scoreDiff > maxDiff) {
            maxDiff = scoreDiff;
            candidRyans = new ArrayList<>();
            candidRyans.add(ryan.clone());
        } else if (scoreDiff == maxDiff) {
            candidRyans.add(ryan.clone());
        }
    }

    int calcDiff(int idx, int diff) {
        if(ryan[idx] > apeach[idx]) {
            if (apeach[idx] == 0) {
                return diff + 10 - idx;
            } else if (apeach[idx] > 0) {
                return diff + (10 - idx) * 2;
            }
        } else {
            return diff;
        }
        return diff;
    }

    void dfs(int idx, int rem, int scoreDiff) {
        if (rem<0) {return;}
        if (rem == 0) {onEnd(scoreDiff);}
        if (idx != 11) { 
            for(int cnt = apeach[idx] + 1; cnt >=0; cnt--) {
                ryan[idx] += cnt;
                dfs(idx+1, rem - cnt, calcDiff(idx, scoreDiff));
                ryan[idx] -= cnt;
            }
        } 
    }

    int apeachScore() {
        int ret = 0;
        for(int i = 0; i < 11; i++) {
            if (apeach[i] > 0) {ret += 10-i;}
        }
        return ret;
    }

    int[] oneTrueRyan() { 
        for (int i = 10; i>=0; i--) {
            if(candidRyans.size()==1) {break;}
            ArrayList<int[]> nextRyans = new ArrayList<>();
            int maxI = 0;
            for (int[] ryan : candidRyans) {
                maxI = Math.max(ryan[i], maxI);
            }
            for(int[]ryan: candidRyans) {
                if (ryan[i] == maxI) {
                    nextRyans.add(ryan);
                }
            }
            candidRyans = nextRyans;
        }
        return candidRyans.get(0);
    }

    public int[] solution(int n, int[] info) {
        this.apeach = info;
        dfs(0, n, -apeachScore());
        if (maxDiff == 0) {
            return new int[] {-1};
        }
        return oneTrueRyan();
    }
}
1 개의 답변
미소미소된장국

완전 탐색으로 풀어도 4ms 가 넘지 않습니다.
똑같이 자바고요.
코드에 불필요한 부분 혹은 복잡해 보이는 부분이 있습니다.
문제를 해결 하고 난 뒤에 AI에게 코드리뷰를 부탁하고 뭐가 최적화가 되었는지 공부하는 방식을 저는 하고 있습니다.

답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다.