본문 바로가기
코딩 테스트/백준

1766 문제집

by 위그든씨 2025. 3. 14.

민오는 1번부터 N번까지 총 N개의 문제로 되어 있는 문제집을 풀려고 한다. 문제는 난이도 순서로 출제되어 있다. 즉 1번 문제가 가장 쉬운 문제이고 N번 문제가 가장 어려운 문제가 된다.

어떤 문제부터 풀까 고민하면서 문제를 훑어보던 민오는, 몇몇 문제들 사이에는 '먼저 푸는 것이 좋은 문제'가 있다는 것을 알게 되었다. 예를 들어 1번 문제를 풀고 나면 4번 문제가 쉽게 풀린다거나 하는 식이다. 민오는 다음의 세 가지 조건에 따라 문제를 풀 순서를 정하기로 하였다.

  1. N개의 문제는 모두 풀어야 한다.
  2. 먼저 푸는 것이 좋은 문제가 있는 문제는, 먼저 푸는 것이 좋은 문제를 반드시 먼저 풀어야 한다.
  3. 가능하면 쉬운 문제부터 풀어야 한다.

예를 들어서 네 개의 문제가 있다고 하자. 4번 문제는 2번 문제보다 먼저 푸는 것이 좋고, 3번 문제는 1번 문제보다 먼저 푸는 것이 좋다고 하자. 만일 4-3-2-1의 순서로 문제를 풀게 되면 조건 1과 조건 2를 만족한다. 하지만 조건 3을 만족하지 않는다. 4보다 3을 충분히 먼저 풀 수 있기 때문이다. 따라서 조건 3을 만족하는 문제를 풀 순서는 3-1-4-2가 된다.

문제의 개수와 먼저 푸는 것이 좋은 문제에 대한 정보가 주어졌을 때, 주어진 조건을 만족하면서 민오가 풀 문제의 순서를 결정해 주는 프로그램을 작성하시오.

입력

첫째 줄에 문제의 수 N(1 ≤ N ≤ 32,000)과 먼저 푸는 것이 좋은 문제에 대한 정보의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 둘째 줄부터 M개의 줄에 걸쳐 두 정수의 순서쌍 A,B가 빈칸을 사이에 두고 주어진다. 이는 A번 문제는 B번 문제보다 먼저 푸는 것이 좋다는 의미이다.

항상 문제를 모두 풀 수 있는 경우만 입력으로 주어진다.

출력

첫째 줄에 문제 번호를 나타내는 1 이상 N 이하의 정수들을 민오가 풀어야 하는 순서대로 빈칸을 사이에 두고 출력한다.

===

문제 분석

처음에 이 문제의 해석을 잘못하여 오답을 제출하였다.

1번 문제의 선행이 5번 문제라면, 5번을 먼저 풀고 1번을 푸는 것으로 생각하여 gr[1] 에 5를 추가한 뒤 DFS 방식으로 1번 문제 풀 때 gr[1]에 담긴 수들을 DFS에 또 담으면서 하나하나 answer에 담아주고 마지막에 1번을 담아줬다. 

하지만 문제에서 요구하는 방식은 1번 문제를 풀 타이밍에 5번 문제를 풀고 나중에 5번 문제를 풀어야할 때 1번 문제를 풀라는거였다.

때문에 선행 문제가 담긴 번호들에 대하여 depth를 줘서 0이 되는 문제라면 최소 힙 큐에 답아주고 문제 번호가 작은 것들부터 pop 해준 뒤 바로 answer에 담는 것으로 문제를 해결하였다.

우선, 입력에 주어진 것들을 그래프와 inDepth에 담아서 풀 수 있는 문제들부터 최소힙에 담아줬다.

const [n, _] = input[0].split(' ').map(Number);
const arr = input.slice(1).map((s) => s.split(' ').map(Number));
const answer = [];

const gr = Array.from({ length: n + 1 }, () => []);
const inDepth = Array.from({ length: n + 1 }).fill(0);

for (const [prev, next] of arr) {
    gr[prev].push(next);
    inDepth[next] += 1;
}
const minHeapq = heapq();
for (let problem = 1; problem < n + 1; problem++) {
    if (inDepth[problem] === 0) {
        minHeapq.push([problem]);
    }
}

이후 최소 힙에서 문제를 하나씩 pop해주고 그 문제와 연계 된 후행 문제들에 대하여 depth를 -1씩 해줬다.

depth가 0이 됐다는 것은 이제 그 문제를 풀기 위한 선행들을 다 푼 것이므로 힙큐에 담아주면 된다.

while (!minHeapq.isEmpty()) {
    const [current] = minHeapq.pop();

    answer.push(current);

    for (const next of gr[current]) {
        if (inDepth[next] === 0) continue;
        inDepth[next] -= 1;

        if (inDepth[next] === 0) {
            minHeapq.push([next]);
        }
    }
}

console.log(answer.join(' '));

전체 코드

const heapq = () => {
    const nodes = [[]];

    const isEmpty = () => nodes.length === 1;

    const swap = (target, destiny) => {
        const temp = nodes[target];
        nodes[target] = [...nodes[destiny]];
        nodes[destiny] = [...temp];
    };
    const print = () => {
        console.log(nodes);
    };

    const push = (node) => {
        nodes.push(node);
        let cur = nodes.length - 1;
        while (cur > 1) {
            const parent = Math.floor(cur / 2);
            if (nodes[parent][0] > nodes[cur][0]) {
                swap(parent, cur);
                cur = parent;
            } else {
                break;
            }
        }
    };

    const pop = () => {
        const data = [...nodes[1]];
        const temp = nodes.pop();
        if (isEmpty()) {
            return data;
        }
        nodes[1] = [...temp];
        let cur = 1;
        while (true) {
            let left = cur * 2;
            let right = left + 1;
            let smallest = cur;
            if (left < nodes.length && nodes[left][0] < nodes[smallest][0]) {
                smallest = left;
            }
            if (right < nodes.length && nodes[right][0] < nodes[smallest][0]) {
                smallest = right;
            }
            if (smallest === cur) break;
            swap(cur, smallest);
            cur = smallest;
        }

        return data;
    };

    return {
        print,
        push,
        pop,
        isEmpty,
    };
};

const input = require('fs')
    .readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
    .toString()
    .trim()
    .split('\n');

const [n, _] = input[0].split(' ').map(Number);
const arr = input.slice(1).map((s) => s.split(' ').map(Number));
const answer = [];

const gr = Array.from({ length: n + 1 }, () => []);
const inDepth = Array.from({ length: n + 1 }).fill(0);

for (const [prev, next] of arr) {
    gr[prev].push(next);
    inDepth[next] += 1;
}
const minHeapq = heapq();
for (let problem = 1; problem < n + 1; problem++) {
    if (inDepth[problem] === 0) {
        minHeapq.push([problem]);
    }
}

while (!minHeapq.isEmpty()) {
    const [current] = minHeapq.pop();

    answer.push(current);

    for (const next of gr[current]) {
        if (inDepth[next] === 0) continue;
        inDepth[next] -= 1;

        if (inDepth[next] === 0) {
            minHeapq.push([next]);
        }
    }
}

console.log(answer.join(' '));