250314 음악프로그램

Jongleee·2025년 3월 14일
0

TIL

목록 보기
837/859
@SuppressWarnings("unchecked")
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());

	List<Integer>[] graph = new ArrayList[n + 1];
	int[] inDegree = new int[n + 1];

	for (int i = 1; i <= n; i++) {
		graph[i] = new ArrayList<>();
	}

	for (int i = 0; i < m; i++) {
		st = new StringTokenizer(br.readLine());
		int count = Integer.parseInt(st.nextToken());
		int prev = Integer.parseInt(st.nextToken());

		for (int j = 1; j < count; j++) {
			int curr = Integer.parseInt(st.nextToken());
			graph[prev].add(curr);
			inDegree[curr]++;
			prev = curr;
		}
	}

	List<Integer> order = topologicalSort(n, graph, inDegree);

	if (order.size() != n) {
		System.out.println(0);
	} else {
		for (int singer : order) {
			sb.append(singer).append("\n");
		}
		System.out.print(sb);
	}
}

private static List<Integer> topologicalSort(int n, List<Integer>[] graph, int[] inDegree) {
	Queue<Integer> queue = new ArrayDeque<>();
	List<Integer> result = new ArrayList<>();

	for (int i = 1; i <= n; i++) {
		if (inDegree[i] == 0) {
			queue.add(i);
		}
	}

	while (!queue.isEmpty()) {
		int node = queue.poll();
		result.add(node);

		for (int next : graph[node]) {
			if (--inDegree[next] == 0) {
				queue.add(next);
			}
		}
	}

	return result;
}

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

0개의 댓글

관련 채용 정보