- 题目
08-图8 How Long Does It Take (25分) 分析
典型的拓扑排序问题。大致的解法如下:
我的代码
#include <stdio.h>
#define MAXN 100
#define INF 1234567
int graph[MAXN][MAXN];
int inDegree[MAXN] = {0};
int earliest[MAXN];
struct Queue{
int front;
int end;
int arrays[MAXN];
}que;
void queInit(){
que.front = -1;
que.end = 0;
}
int quePop(){
return que.arrays[++que.front];
}
void quePush(int x){
que.arrays[que.end++] = x;
}
int queEmpty(){
return que.end-que.front == 1;
}
int topSort(int N){
int cnt = 0;
queInit();
for (int i=0; i<N; i++) {
if(inDegree[i] == 0) {
quePush(i);
earliest[i] = 0;
}
}
while (!queEmpty()) {
int p = quePop();
cnt++;
for (int i=0; i<N; i++) {
if(graph[p][i]!=0 && graph[p][i]!=INF){
inDegree[i]--;
if(earliest[p]+graph[p][i] > earliest[i]){
earliest[i] = earliest[p]+graph[p][i];
}
if (inDegree[i] == 0) {
quePush(i);
}
}
}
}
if(cnt < N) return 0;
return 1;
}
int main(int argc, const char * argv[]) {
int N, M;
scanf("%d%d", &N, &M);
//init graph
for(int i=0; i<N; i++){
for (int j=0; j<N; j++) {
if (i == j) {
graph[i][j] = 0;
}else{
graph[i][j] = INF;
}
}
}
//read data
int x,y,weight;
for(int i=0; i<M; i++){
scanf("%d%d%d", &x, &y, &weight);
graph[x][y] = weight;//有向图
}
//init inDegree[]
for(int i=0; i<N; i++){
for (int j=0; j<N; j++) {
if(graph[i][j]!=0 && graph[i][j]!=INF)
inDegree[j]++;
}
}
//init earliest[]
for(int i=0; i<N; i++) earliest[i] = -1;
int ans = topSort(N);
int max = 0;
if(ans == 0) printf("Impossible\n");
else{
for(int i=0; i<N; i++) {
// printf("%d\n", earliest[i]);
if(earliest[i] > max) max = earliest[i];
}
printf("%d\n", max);
}
return 0;
}