티스토리 뷰

 

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

 

2623번: 음악프로그램

첫째 줄에는 가수의 수 N과 보조 PD의 수 M이 주어진다. 가수는 번호 1, 2,…,N 으로 표시한다. 둘째 줄부터 각 보조 PD가 정한 순서들이 한 줄에 하나씩 나온다. 각 줄의 맨 앞에는 보조 PD가 담당한

www.acmicpc.net

예전에 학원 다닐 때, 선생님이 한 번 풀어보라고 했던 문제라서 기억이 난다. 

그 때는 진짜 어떻게 풀어야될지 감이 안 왔는데,

이제 꽤 쉽게 풀린다. 

 

감회가 새롭다. 

 

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;
        }
}

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

const [N, M] = input.shift();
let indegree = Array(N + 1).fill(0);
const adj = Array.from(Array(N + 1), () => []);
input.forEach((v) => {
        for (let i = 1; i < v.length - 1; i++) {
                indegree[v[i + 1]]++;
                adj[v[i]].push(v[i + 1]);
        }
});

const q = new Queue();

for (let i = 1; i < indegree.length; i++) {
        if (indegree[i] == 0) q.push(i);
}

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

        for (let i = 0; i < adj[node].length; i++) {
                indegree[adj[node][i]]--;
                if (indegree[adj[node][i]] == 0) q.push(adj[node][i]);
        }
}

if (answer.length != N) console.log(0);
else console.log(answer.join('\n'));
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
글 보관함