chenxi16

导航

数据结构1 - 08-图8 How Long Does It Take

 

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define MAXN 100
 4 #define INF 0x3fffffff
 5 int n,m,g[MAXN][MAXN],indegree[MAXN],ve[MAXN];
 6 void read();
 7 int topsort(); 
 8 int main(){
 9     int cost;
10     read();
11     cost = topsort();
12     if(cost==-1) printf("Impossible\n");
13     else printf("%d",cost);
14     return 0;
15 }
16 void read(){
17     scanf("%d %d",&n,&m);
18     int i,j,v1,v2,lastime;
19     for(i=0;i<n;i++)
20         for(j=0;j<n;j++)
21             g[i][j] = INF;
22     for(i=0;i<n;i++) indegree[i]=0;
23     for(i=0;i<m;i++){
24         scanf("%d %d %d",&v1,&v2,&lastime);
25         g[v1][v2] = lastime;
26         indegree[v2]++;
27     }
28 }
29 int topsort(){
30     int i,j,count=0,seq[MAXN];
31     int cost,time,point;
32     for(i=0;i<n;i++) ve[i] = 0;
33     j=0;
34     for(i=0;i<n;i++){
35         if(indegree[i]==0)seq[j++] = i;
36     }
37     count = j;
38     j=0;
39     while(count>j){
40         point = seq[j];
41         j++;
42         for(i=0;i<n;i++){
43             if(g[point][i]!=INF&&i!=point){
44                 indegree[i]--;
45                 if(ve[i]<ve[point]+g[point][i])
46                     ve[i] = ve[point]+g[point][i];
47                 if(indegree[i]==0){
48                     seq[count++] = i;
49                 }
50             }
51         }
52         
53     }
54     if(count==n){
55         cost = 0;
56         for(i=0;i<n;i++){
57             if(cost<ve[i]) cost = ve[i];
58         }
59         return cost;
60     }
61     else return -1;
62         
63 }
View Code

 

posted on 2020-04-05 20:24  chenxi16  阅读(141)  评论(0编辑  收藏  举报