拓扑排序
来源:互联网 发布:法语之言能无从乎 编辑:程序博客网 时间: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 N (≤100), the number of activity check points (hence it is assumed that the check points are numbered from 0 to N−1), and M, the number of activities. Then M 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;}}
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 【拓扑排序】
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- Android error: “Apostrophe not preceded by \” 解决办法
- 5064. 友好城市
- 浅谈mysql的搜索引擎之MyISAM和InnoDB的异同
- python使用遇到的问题
- 构造函数
- 拓扑排序
- A
- 在vs中安装Easyx图形库(仅c++)
- C语言计算文件MD5
- Linux学习之十四章设备的访问
- 2017 Wuhan University Programming Contest 现场赛 I.A simple math problem(矩阵快速幂)
- win10下U盘安装fedora25
- 在CentOS 6.6 64bit上升级GCC到4.8.2版本
- bzoj 4475: [Jsoi2015]子集选取 数学