pat06-图7. How Long Does It Take (25)

06-图7. How Long Does It Take (25)

时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

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

提交代码

 

AOV图。拓扑排序。

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<queue>
 6 #include<vector>
 7 #include<cmath>
 8 #include<string>
 9 using namespace std;
10 int Map[105][105],dist[105],indegree[105];
11 int main(){
12     //freopen("D:\\INPUT.txt","r",stdin);
13     int n,m;
14     int i,j,a,b,cost;
15     scanf("%d %d",&n,&m);
16     for(i=0;i<n;i++){
17         dist[i]=-1;
18         indegree[i]=0;
19         for(j=0;j<n;j++){
20             Map[i][j]=Map[j][i]=-1;
21         }
22     }
23     for(i=0;i<m;i++){
24         scanf("%d %d %d",&a,&b,&cost);
25         Map[a][b]=cost;
26         indegree[b]++;
27     }
28     queue<int> q;
29     for(i=0;i<n;i++){
30         if(!indegree[i]){
31             q.push(i);
32             dist[i]=0;//这个初始化很重要
33         }
34     }
35     int cur;
36     while(!q.empty()){
37         cur=q.front();
38         q.pop();
39         for(i=0;i<n;i++){
40             if(Map[cur][i]!=-1){
41                indegree[i]--;
42                if(dist[cur]+Map[cur][i]>dist[i]){
43                     dist[i]=dist[cur]+Map[cur][i];
44                 }
45                if(!indegree[i]){
46                     q.push(i);
47                }
48             }
49         }
50     }
51     int maxcost=-1;
52     for(i=0;i<n;i++){
53         if(indegree[i]){
54             break;
55         }
56         if(dist[i]>maxcost){
57             maxcost=dist[i];
58         }
59     }
60     if(i==n){
61         printf("%d\n",maxcost);
62     }
63     else{
64         printf("Impossible\n");
65     }
66     return 0;
67 }

 

posted @ 2015-08-25 02:59  Deribs4  阅读(361)  评论(0编辑  收藏  举报