1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 101 4 struct edge{ 5 int v,e,l,time; 6 }; 7 struct adjs{ 8 struct edge ed[MAXN]; 9 struct edge ed2[MAXN]; 10 int len; 11 int count; 12 }; 13 struct adjs adj[MAXN]; 14 int ve[MAXN],vl[MAXN],seq[MAXN],start,end; 15 int m,n,indegree[MAXN]; 16 void read(); 17 int tops(); 18 int main(){ 19 int i,j,v1,v2,time,etime; 20 read(); 21 etime = tops(); 22 if(etime!=-1){ 23 printf("%d\n",etime); 24 for(i=1;i<=n;i++){ 25 v1 = i; 26 for(j=adj[i].count-1;j>=0;j--){ 27 v2 = adj[v1].ed[j].v; 28 time = adj[v1].ed[j].time; 29 adj[v1].ed[j].l = vl[v2]-time; 30 adj[v1].ed[j].e = ve[v1]; 31 if(adj[v1].ed[j].l==adj[v1].ed[j].e){ 32 printf("%d->%d\n",v1,v2); 33 } 34 } 35 } 36 37 } 38 else printf("0\n"); 39 return 0; 40 } 41 void read(){ 42 scanf("%d %d",&n,&m); 43 int i,j,v1,v2,lastime; 44 for(i=0;i<MAXN;i++) { 45 adj[i].count=0; 46 adj[i].len=0; 47 } 48 for(i=0;i<=n;i++) indegree[i]=0; 49 adj[0].count = m; 50 for(i=1;i<=m;i++){ 51 scanf("%d %d %d",&v1,&v2,&lastime); 52 adj[v1].ed[adj[v1].count].v = v2; 53 adj[v1].ed[adj[v1].count].time = lastime; 54 adj[v1].ed[adj[v1].count].e=0; 55 adj[v1].ed[adj[v1].count].l=0; 56 adj[v1].count++; 57 indegree[v2]++; 58 59 adj[v2].ed2[adj[v2].len].v=v1; 60 adj[v2].ed2[adj[v2].len].time=lastime; 61 adj[v2].len++; 62 } 63 } 64 int tops(){ 65 int i,j,value,v1,v2,time,etime; 66 for(i=1;i<=n;i++){ 67 ve[i] = 0; 68 } 69 start=0; 70 end =0; 71 for(i=1;i<=n;i++) 72 if(indegree[i]==0) seq[end++]=i; 73 74 //ve计算 75 while(start<end){ 76 v1 = seq[start]; 77 start++; 78 for(i=0;i<adj[v1].count;i++){ 79 v2 = adj[v1].ed[i].v; 80 time = adj[v1].ed[i].time; 81 indegree[v2]--; 82 if(indegree[v2]==0) seq[end++] = v2; 83 if((ve[v1]+time)>ve[v2]){ 84 ve[v2] = ve[v1]+time; 85 } 86 } 87 } 88 89 if(end!=n) return -1; 90 etime = 0; 91 for(i=1;i<=n;i++){ 92 if(ve[i]>etime) etime = ve[i]; 93 } 94 //vl 计算c 95 for(i=1;i<=n;i++) vl[i] = etime; 96 start = end-1; 97 while(end>=0){ 98 v2 = seq[end--]; 99 for(i=0;i<adj[v2].len;i++){ 100 v1 = adj[v2].ed2[i].v; 101 time = adj[v2].ed2[i].time; 102 if(vl[v1]>(vl[v2]-time)){ 103 vl[v1] = vl[v2]-time; 104 } 105 } 106 } 107 return etime; 108 }View Code