拓扑排序-图8 How Long Does It Take

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值