考研数据结构练手三:关键路径。

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, m, i, j, k;
    int *G;
    int *Q, *E, *L;
    
    scanf("%d", &n);
    G = (int*)calloc((n + 1) * n + 1, sizeof(int));
    Q = (int*)calloc(n, sizeof(int));
    E = (int*)calloc(n, sizeof(int));
    L = (int*)calloc(n, sizeof(int));
    memset(G, 0, sizeof(G));
    
    while(1)
    {
        scanf("%d %d %d", &i, &j, &k);
        if(i == 0 || j == 0) break;
        G[i * n + j] = k;
        G[j]++;
    }
    
    for(m = 0; m < n; m++)
    {
        for(i = 1; i <= n; i++)
        {
            if(G[i] == -1)
                continue;
            if(G[i] == 0)
                break;
        }
        Q[m] = i;
        G[i] = -1;
        for(j = 1; j <= n; j++)
            if(G[i * n + j] > 0)
                                G[j]--;
    }

    for(m = 0; m < n; m++)
        for(i = 0; i < m ; i++)
            if(G[Q[i] * n + Q[m]] > 0 && E[Q[m] - 1] < E[Q[i] - 1] + G[Q[i] * n + Q[m]])
                E[Q[m] - 1] = E[Q[i] - 1] + G[Q[i] * n + Q[m]];

    L[Q[n - 1] - 1] = E[Q[n - 1] - 1];
    for(m = n - 2; m >= 0; m--)
    {
                L[Q[m] - 1] = -1;
        for(i = n - 1; i > m ; i--)
            if(G[Q[m] * n + Q[i]] > 0 && (L[Q[m] - 1] == -1 || L[Q[m] - 1] > L[Q[i] - 1] - G[Q[m] * n + Q[i]]))
                L[Q[m] - 1] = L[Q[i] - 1] - G[Q[m] * n + Q[i]];
    }

    for(m = 0; m < n; m++)
            if(E[Q[m] - 1] == L[Q[m] - 1])
                    printf("%d\n",Q[m]);

    free(G);
    free(Q);
    free(E);
    free(L);

    return 0;
}