Thief of Wealth

문제

민오는 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 이하의 정수들을 민오가 풀어야 하는 순서대로 빈칸을 사이에 두고 출력한다.

 

 

핵심 아이디어

알맞은 순서대로 문제를 풀어야 하는 전형적인 위상정렬 문제이다.

위상정렬 문제를 푸는 것처럼 간선을 추가하고 entry count를 센다.

그리고, entry count가 0인 것 중, 가장 낮은 수의 문제를 풀고 

그것의 간선을 파악하여 entry count를 줄여준다.

이를 반복하면 위상정렬로 문제를 풀 수 있다.

 

'use strict'

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

class PQ {
    constructor(size) {
        this.node = 1;
        this.tree = new Array(size + 1).fill(0);
    }

    push(val) {
        const {
            tree
        } = this;
        if (this.node >= tree.length) {
            console.log('overflow');
            return;
        }

        tree[this.node] = val;
        this.node += 1;
        let child = this.node - 1;

        while (child > 1) {
            const parent = Math.floor(child / 2);
            if (tree[child] < tree[parent]) { // 정렬 기준
                const temp = tree[child];
                tree[child] = tree[parent];
                tree[parent] = temp;
            } else {
                break;
            }
            child = parent;
        }
    }

    isEmpty() {
        return this.node <= 1;
    }

    pop() {
        const {
            tree
        } = this;
        if (this.node <= 1) {
            // console.log('empty');
            return;
        }

        const popped = tree[1];
        tree[1] = tree[this.node - 1];
        this.node -= 1;
        let parent = 1;

        while (parent < this.node - 1) {
            let child = -1;
            if (parent * 2 >= this.node) {
                break;
            } else if (parent * 2 < this.node && parent * 2 + 1 >= this.node) {
                child = parent * 2;
            } else {
                if (tree[parent * 2] < tree[parent * 2 + 1]) {
                    child = parent * 2;
                } else {
                    child = parent * 2 + 1;
                }
            }

            if (tree[child] < tree[parent]) {
                const temp = tree[child];
                tree[child] = tree[parent];
                tree[parent] = temp;
                parent = child;
            } else {
                break;
            }
        }
        return popped;
    }
}

// 위상정렬
const solution = function (input) {
    const [n, m] = input[0].split(" ").map(elem => parseInt(elem));

    // 간선을 추가한다
    const edges = [...new Array(n + 1)].map(() => []);
    const entryCount = new Array(n + 1).fill(0);
    const ans = [];

    input.slice(1).forEach(element => {
        const [start, end] = element.split(" ").map(elem => parseInt(elem));
        edges[start].push(end);
        entryCount[end]++;
    });

    const q = new PQ(n + 1);
    // entry가 0인 문제를 찾는다.
    for (let i = 1; i < n + 1; i++) {
        if (entryCount[i] === 0) {
            q.push(i);
            entryCount[i]--; // -1로 만들어줌
        }
    }
    while (!q.isEmpty()) {
        // 간선을 이용해서 entry를 줄인다
        const first = q.pop();

        ans.push(first);
        edges[first].forEach(
            dest => {
                entryCount[dest]--;
                if (entryCount[dest] === 0) {
                    q.push(dest);
                    entryCount[dest]--; // -1로 만들어줌
                }
            }
        );


    }

    console.log(ans.join(' '));
};


const input = [];
rl.on("line", function (line) {
    input.push(line);
}).on("close", function () {
    solution(input);
    process.exit();
});
profile on loading

Loading...