拓扑排序

来源:互联网 发布:法语之言能无从乎 编辑:程序博客网 时间:2024/06/06 02:20

为了避免每次都遍历找未输出的入度为0的顶点,直接维持一个Queue,每次删除节点时有入度为0的顶点,就把它放到Queue里面去




例子:

Given the relations of all the activities of a project, you are supposed to find the earliest completion time of the project.

Input Specification:

Each input file contains one test case. Each case starts with a line containing two positive integers NNN (≤100\le 100100), the number of activity check points (hence it is assumed that the check points are numbered from 0 to N−1N-1N1), and MMM, the number of activities. Then MMM lines follow, each gives the description of an activity. For the i-th activity, three non-negative numbers are given: S[i]E[i], and L[i], where S[i] is the index of the starting check point, E[i] of the ending check point, and L[i] the lasting time of the activity. The numbers in a line are separated by a space.

Output Specification:

For each test case, if the scheduling is possible, print in a line its earliest completion time; or simply output "Impossible".

Sample Input 1:

9 120 1 60 2 40 3 51 4 12 4 13 5 25 4 04 6 94 7 75 7 46 8 27 8 4

Sample Output 1:

18

Sample Input 2:

4 50 1 10 2 22 1 31 3 43 2 5

Sample Output 2:

Impossible


思路:完成某件事有条件,所以拓扑排序,但也不是普通的拓扑排序,不同之处在于有权重,所以需要维持一个权重和数组,但是基本的流程是按照拓扑排序来的,因为这个过程反应的就是pre-requirement

public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt(), m = sc.nextInt();        int[][] adj = new int[n][n];        for(int[] a : adj)Arrays.fill(a, -1);        for(int i=0; i<m; i++)         adj[sc.nextInt()][sc.nextInt()] = sc.nextInt();                // topsort        int rst = topsort(adj, n);        if(rst == -1)        System.out.println("Impossible");        else        System.out.println(rst);    }private static int topsort(int[][] adj, int n) {int[] indegree = new int[n];for(int i=0; i<n; i++)for(int j=0; j<n; j++)if(adj[i][j] != -1)indegree[j] ++;Queue<Integer> q = new LinkedList<Integer>();int[] costs = new int[n];for(int i=0; i<n; i++)if(indegree[i] == 0)q.add(i);int cnt = 0, longest = -1;while(!q.isEmpty()) {int i = q.remove();cnt ++;for(int j=0; j<n; j++)if(adj[i][j] != -1 && indegree[j] != 0) {indegree[j] --;if(indegree[j] == 0)q.add(j);costs[j] = Math.max(costs[j], costs[i]+adj[i][j]);longest = Math.max(longest, costs[j]);// 终点可能不是最后那个index,也可能有多个}}return cnt == n ? longest : -1;}}


0 0
原创粉丝点击