一、题目
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 12
0 1 6
0 2 4
0 3 5
1 4 1
2 4 1
3 5 2
5 4 0
4 6 9
4 7 7
5 7 4
6 8 2
7 8 4
Sample Output 1:
18
Sample Input 2:
4 5
0 1 1
0 2 2
2 1 3
1 3 4
3 2 5
Sample Output 2:
Impossible
二、解答
import java.util.*;
public class Main {
public static void main(String[] args) {
//获取数据
Scanner sc = new Scanner(System.in);
int nodeNum = sc.nextInt(), actNum = sc.nextInt();
int[][] map = new int[nodeNum][nodeNum];
for (int i = 0; i < actNum; i++) { map[sc.nextInt()][sc.nextInt()] = sc.nextInt();}
//统计每个结点的入度数
int[] parNum = new int[nodeNum];
for (int i = 0; i < nodeNum; i++) {
for (int j = 0; j < nodeNum; j++) {
if (map[j][i] > 0) parNum[i]++;
}
}
//开始拓扑排序
int count = 0;
boolean[] visited = new boolean[nodeNum];
int[] times = new int[nodeNum]; //存放到达各个结点的时间
ArrayList<Integer> noPar = new ArrayList<>(); //存放各个结点的入度数
for (int i = 0; i < nodeNum; i++) {
if (parNum[i] == 0) {
noPar.add(i);
visited[i] = true;
count++;
}
}
while (noPar.size() != 0) {
int curNode = noPar.remove(0);
for (int i = 0; i < nodeNum; i++) {
if (map[curNode][i] > 0 && times[curNode] + map[curNode][i] > times[i]) times[i] = times[curNode] + map[curNode][i];
if (map[curNode][i] > 0) parNum[i]--;
if (parNum[i] == 0 && visited[i] == false) {
noPar.add(i);
visited[i] = true;
count++;
}
}
}
//输出结果:输出时间最大值,而不是结点最后一个的值
int max = 0;
for (int i = 0; i < nodeNum; i++) { if (times[i] > max) max = times[i];}
if (count == nodeNum) System.out.println(max);
else System.out.println("Impossible");
}
}
思路:
- 什么类型的问题?工序问题,一步一步走,需要使用拓扑排序
- 如何实现拓扑排序?每次操作都取入度为0的结点,剔除结点
- 注意输出:要求输出的是花费的最大时间,而不是索引最大的结点