본문 바로가기
알고리즘

위상정렬 (Topological Sort)

by 출근길 2018. 7. 17.

package boj;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class TopologicalSort {
	/*
	 * BOJ 1516 게임 개발
	 * https://www.acmicpc.net/problem/1516
	 */

	public static void main(String[] args) throws IOException {
		System.setIn(new FileInputStream("res/seminar/boj1516.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer ST;
		
		
		int N = Integer.parseInt(br.readLine());
		int[] time = new int[N+1];
		int[] result = new int[N+1];
		int[] inDegree = new int[N+1];
		
		
		ArrayList[] outList = new ArrayList[N+1];
		for (int i = 1; i <= N; i++){
			outList[i] = new ArrayList();
		}
		
		for (int i = 1; i <= N; i++){
			ST = new StringTokenizer(br.readLine());
			
			int n = Integer.parseInt(ST.nextToken());
			time[i] = n;
			result[i] = n;
			while(ST.hasMoreTokens()){
				int next = Integer.parseInt(ST.nextToken());
				if(next == -1) break;
				outList[next].add(i);
				inDegree[i]++;
			}
		}
		
		Queue que = new LinkedList();
		for (int i = 1; i <= N; i++){
			if (inDegree[i] == 0){
				que.add(i);
			}
		}
		
		while (!que.isEmpty()){
			int cur = que.poll();
			for (int next : outList[cur]){
				result[next] = Math.max(result[next], result[cur]+time[next]);
				inDegree[next]--;
				if (inDegree[next] == 0){
					que.add(next);
				}
			}
		}
		
		for (int i = 1; i <= N; i++){
			bw.write(result[i]+"\n");
		}
		
		
		
		br.close();
		bw.flush();
		bw.close();
	}

}



'알고리즘' 카테고리의 다른 글

에라토스 테네스의 체  (0) 2018.07.18
최소 공통 조상(LCA : Lowest Common Ancestor)  (0) 2018.07.18
페르마의 소정리  (0) 2018.07.17
Union-Find  (0) 2018.07.17
SPFA (Shortest Path Faster Algorithm)  (0) 2018.07.17
인덱스 트리 (Indexed Tree)  (0) 2018.07.17
플로이드 워셜 (Floyd Warshall)  (0) 2018.07.17
다익스트라 (Dijkstra)  (0) 2018.07.17