#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define Maxn 105
#define INF -100005
typedef struct AdjNode* AdjList;
struct AdjNode {
int index;
int Weight;
AdjList Next;
};
typedef struct HNode {
AdjList FirstEdge;
}List[Maxn];
typedef struct GNode* LGraph;
struct GNode {
int Nv;
List Head;
};
typedef struct ENode* Edge;
struct ENode {
int V1, V2;
int Weight;
};
void InsertEdge(LGraph G, Edge E) {
AdjList NewNode;
NewNode = (AdjList)malloc(sizeof(struct AdjNode));
NewNode->index = E->V2;
NewNode->Weight = E->Weight;
NewNode->Next = G->Head[E->V1].FirstEdge;
G->Head[E->V1].FirstEdge = NewNode;
}
LGraph CreateLGraph(int n, int m) {
int v;
LGraph G = (LGraph)malloc(sizeof(struct GNode));
Edge E = (Edge)malloc(sizeof(struct ENode));
G->Nv = n;
for(v = 0; v < n; v++)
G->Head[v].FirstEdge = NULL;
for(v = 0; v < m; v++) {
scanf("%d%d%d", &E->V1, &E->V2, &E->Weight);
InsertEdge(G, E);
}
return G;
}
int TopSort(LGraph G) {
int Indegree[Maxn], Time[Maxn], cnt = 0, t = INF;
int Q[Maxn], front, rear;
int v;
AdjList w;
front = rear = 0;
//初始化入度数
for(v = 0; v < G->Nv; v++) {
Time[v] = 0;
Indegree[v] = 0;
}
for(v = 0; v < G->Nv; v++)
for(w = G->Head[v].FirstEdge; w; w = w->Next)
++Indegree[w->index];
for(v = 0; v < G->Nv; v++) if(!Indegree[v]) Q[++rear] = v;
while(rear != front) {
v = Q[++front];
cnt++;
for(w = G->Head[v].FirstEdge; w; w = w->Next) {
if(Time[v] + w->Weight > Time[w->index]) Time[w->index] = Time[v] + w->Weight;
if(--Indegree[w->index] == 0) Q[++rear] = w->index;
}
}//printf("%d\n", cnt);
if(cnt == G->Nv) {
for(v = 0; v < cnt; v++)
if(t < Time[v]) t = Time[v];
printf("%d\n", t);
}
else printf("Impossible\n");
}
int main() {
int n, m;
LGraph G;
scanf("%d%d", &n, &m);
G = CreateLGraph(n, m);
TopSort(G);
return 0;
}
/*
拓扑排序。。第一次写时,把计算时间分开了,错误出现在计算的顺序上,应该按照拓扑顺序来计算出时间的值。
*/
08-图8 How Long Does It Take (25分)
最新推荐文章于 2020-06-27 13:10:54 发布