BOJ_2623_음악프로그램_java
2023. 2. 5. 22:39ㆍAlgorithm/BOJ
728x90
https://www.acmicpc.net/problem/2623
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
백준 2623번 음악프로그램
골드 3
*/
public class BOJ_2623_음악프로그램 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] inDegree = new int[N+1];
List<Integer>[] edges = new List[N+1];
for (int i = 1; i<N+1; i++){
edges[i] = new ArrayList<>();
}
// 간선 정보 입력
for (int i = 0; i<M; i++){
st = new StringTokenizer(br.readLine());
int peopleNum = Integer.parseInt(st.nextToken());
int from = Integer.parseInt(st.nextToken());
for (int j = 1; j<peopleNum; j++){
int to = Integer.parseInt(st.nextToken());
edges[from].add(to);
inDegree[to]++;
from = to;
}
}
// 위상정렬
Queue<Integer> queue = new LinkedList();
int nodeCnt = 0;
for (int i = 1; i<=N; i++){
if (inDegree[i] == 0){
queue.offer(i);
while (!queue.isEmpty()){
int node = queue.poll();
sb.append(node).append("\n");
nodeCnt++;
inDegree[node] = -1;
for (int next : edges[node]){
inDegree[next]--;
if (inDegree[next] == 0){
queue.offer(next);
}
}
}
}
}
if (nodeCnt == N){
System.out.println(sb.toString());
}else {
System.out.println(0);
}
}
}
'Algorithm > BOJ' 카테고리의 다른 글
BOJ_4386_별자리 만들기_java (0) | 2023.02.08 |
---|---|
BOJ_2473_세 용액_java (0) | 2023.02.07 |
BOJ_1005_ACM Craft_java (0) | 2023.02.05 |
BOJ_2252_줄 세우기_java (0) | 2023.02.05 |
BOJ_2143_두 배열의 합 (0) | 2023.02.02 |