• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

가장 높은 탑 쌓기

23.09.08 23:18 작성 조회수 183

0

코드가 왜 오답인지 잘 모르겠습니다ㅠㅠ

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

class Block implements Comparable<Block> {
    int a;
    int h;
    int w;

    public Block(int a, int h, int w) {
        this.a = a;
        this.h = h;
        this.w = w;
    }

    @Override
    public int compareTo(Block o) {
        return o.a - this.a;
    }
}

class Main {
    static int[] dy;
    static int[] dis;

    public int solution(ArrayList<Block> arr, int n) {
        int answer = 0;
        Collections.sort(arr);
        dy[0] = 1;
        dis[0] = arr.get(0).h;
        for (int i = 1; i < n; i++) {
            int max = 0;
            int max_h = 0;
            for (int j = i - 1; j >= 0; j--) {
                if (arr.get(j).w > arr.get(i).w && dy[j] >= max && dis[j] > max_h) {
                    max = dy[j];
                    max_h = dis[j];
                }
            }
            dy[i] = max + 1;
            dis[i] = max_h + arr.get(i).h;
            answer = Math.max(answer, dis[i]);
        }
        return answer;
    }

    public static void main(String[] args) {
        Main T = new Main();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        ArrayList<Block> arr = new ArrayList<Block>();
        dy = new int[n];
        dis = new int[n];
        for (int i = 0; i < n; i++) {
            int a = kb.nextInt();
            int h = kb.nextInt();
            int w = kb.nextInt();
            arr.add(new Block(a, h ,w));
        }
        System.out.println(T.solution(arr, n));
    }
}

답변 1

답변을 작성해보세요.

-1

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.09.10

안녕하세요, 인프런 AI 인턴이에요.

주어진 코드를 보면, 가장 높은 탑을 쌓는 문제를 해결하기 위한 코드인 것 같습니다.
그러나 코드가 오답인 이유는 변수 dydis를 초기화하지 않은 상태에서 사용하고 있기 때문입니다.

해결하기 위해 dydis 배열을 선언하고 초기화해야 합니다.
아래와 같이 solution 함수의 맨 첫 줄에 dy = new int[n];dis = new int[n];을 추가하세요.

public int solution(ArrayList<Block> arr, int n) {
    int answer = 0;
    Collections.sort(arr);
    dy = new int[n]; // 추가
    dis = new int[n]; // 추가
    dy[0] = 1;
    dis[0] = arr.get(0).h;
    // 이하 생략

이렇게 수정하면 오답이 없는 코드가 됩니다.
질문이 더 있으시면 답변해드릴게요.