7-12 How Long Does It Take(25 分)
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
思路:
1、典型的拓扑排序,解决AOE网络问题(关键路径问题)。
2、基本思路是建立图之后,用一个容器存储入度为0的节点(这里用队列),然后poll,遍历他的邻接点,更新邻接点的最晚完成时间,并且入度减1,检测邻接点入度是否为0,是的话,入列。
3、用一个计数器记录poll出的节点数量,当循环完毕的时候,若计数器等于N,则表示所有节点一个不落,图中不存在闭环。这时遍历所有节点,输出最晚完成时间最大的那个值。若计数器小于N,则表示图中有闭环,error。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N;
static int M;
static Node node[];
static int G[][];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner (System.in);
N = in.nextInt();
M = in.nextInt();
G = new int[N][N];
node = new Node[N];
for(int i = 0;i<N;i++)
for(int j = 0;j<N;j++) {
G[i][j] = Integer.MAX_VALUE/10;
}
for(int i = 0;i<N;i++) {
node[i] = new Node(i);
}
for(int i = 0;i<M;i++) {
int x = in.nextInt();
int y = in.nextInt();
G[x][y] = in.nextInt();
node[y].ru++;
}
Queue<Integer> qu = new LinkedList<>();
for(int i = 0;i<N;i++) {
if(node[i].ru==0) {
qu.add(i);
}
}
int count = 0;
while(!qu.isEmpty()) {
int i = qu.poll();count++;
for(int j=0;j<N; j++) {
if(G[i][j]<Integer.MAX_VALUE/10) {
if(node[j].day < node[i].day+G[i][j]) {
node[j].day = node[i].day+G[i][j];
}
node[j].ru--;
if(node[j].ru==0)
qu.add(j);
}
}
}
if(count!=N)
System.out.print("Impossible");
else {
int temp = 0;
for(int i = 0;i<N;i++) {
if(node[i].day>temp) {
temp = node[i].day;
}
}
System.out.print(temp);
}
}
}
class Node{
Node(){
}
Node(int y){
m = y;
}
int m;
int day;
int ru;
}