티스토리 뷰

https://www.acmicpc.net/problem/2252

 

2252번: 줄 세우기

첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의

www.acmicpc.net

 

const input = require('fs')
        .readFileSync('./dev/stdin')
        .toString()
        .trim()
        .split('\n')
        .map((v) => v.split(' ').map(Number));

const [N] = input.shift();

// 들어오는 간선이 없는 놈은??? 키가 작음.

// 들어오는 간선이 없는 정점을 먼저 출력하면 될거 같음.

// 여기에 들어오는 거  몇개 있는지 카운트 하고.
// 들어오는 간선이 없는 정점.. 을 출력할 때마다. 그 놈보다 키가 큰? 정점의 카운트를 1씩 줄여줌.....

let edgeCount = {};
for (let i = 1; i <= N; i++) {
        edgeCount[i] = 0;
}

let giant = Array.from(Array(N + 1), () => []);

input.forEach(([a, b]) => {
        // a가 작은놈.
        giant[a].push(b);
        edgeCount[b] += 1;
});
class Node {
        constructor(item) {
                this.item = item;
                this.next = null;
        }
}

class Queue {
        constructor() {
                this.head = null;
                this.tail = null;
                this.length = 0;
        }

        push(item) {
                const node = new Node(item);
                if (this.head == null) {
                        this.head = node;
                } else {
                        this.tail.next = node;
                }

                this.tail = node;
                this.length += 1;
        }

        pop() {
                const popItem = this.head;
                this.head = this.head.next;
                this.length -= 1;
                return popItem.item;
        }
}

const q = new Queue();

Object.entries(edgeCount).forEach(([key, value]) => {
        if (value == 0) q.push(+key);
});

const answer = [];
while (q.length > 0) {
        const x = q.pop();
        answer.push(x);

        giant[x].forEach((v) => {
                edgeCount[v] -= 1;
                if (edgeCount[v] == 0) q.push(v);
        });
}

console.log(answer.join(' '));
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함