241221 Milk Factory

Jongleee·2024년 12월 21일
0

TIL

목록 보기
762/816
public static void main(String[] args) throws IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

	int n = Integer.parseInt(br.readLine());
	int[] outgoingEdges = new int[n];

	countEdges(br, n, outgoingEdges);
	int root = findRoot(outgoingEdges, n);

	System.out.println(root);
}

private static void countEdges(BufferedReader br, int n, int[] outgoingEdges) throws IOException {
	for (int i = 0; i < n - 1; i++) {
		StringTokenizer st = new StringTokenizer(br.readLine());
		int a = Integer.parseInt(st.nextToken());
		st.nextToken();
		outgoingEdges[a - 1]++;
	}
}

private static int findRoot(int[] outgoingEdges, int n) {
	int root = 0;

	for (int i = 0; i < n; i++) {
		if (root != 0 && outgoingEdges[i] == 0) {
			return -1;
		}
		if (outgoingEdges[i] == 0) {
			root = i + 1;
		}
	}
	return root;
}

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

0개의 댓글

관련 채용 정보