跳转至

拓扑排序注意点

Given the relations of all the activities of a project, you are supposed to find the earliest completion time of the project. Input Specification:

Each input file contains one test case. Each case starts with a line containing two positive integers N (<=100), the number of activity check points (hence it is assumed that the check points are numbered from 0 to N-1), and M, the number of activities. Then M lines follow, each gives the description of an activity. For the i-th activity, three non-negative numbers are given: S[i], E[i], and L[i], where S[i] is the index of the starting check point, E[i] of the ending check point, and L[i] the lasting time of the activity. The numbers in a line are separated by a space. Output Specification: For each test case, if the scheduling is possible, print in a line its earliest completion time; or simply output "Impossible*

example:

9 12

0 1 6

0 2 4

0 3 5

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

#define MAX_N 100

typedef struct {
    int start;
    int end;
    int duration;
} Activity;

int earliest_completion_time(int N, int M, Activity activities[]) {
    int graph[MAX_N][MAX_N] = {0};
    int in_degree[MAX_N] = {0};
    int earliest_start_time[MAX_N] = {0};
    int queue[MAX_N];
    int front = 0, rear = 0;

    for (int i = 0; i < M; i++) {
        graph[activities[i].start][activities[i].end] = activities[i].duration;
        in_degree[activities[i].end]++;
    }

    for (int i = 0; i < N; i++) {
        if (in_degree[i] == 0) {
            queue[rear++] = i;
        }
    }

    while (front < rear) {
        int current = queue[front++];

        for (int neighbor = 0; neighbor < N; neighbor++) {
            if (graph[current][neighbor] > 0) {
                in_degree[neighbor]--;
                earliest_start_time[neighbor] =               
                    max(earliest_start_time[neighbor],
                        earliest_start_time[current] + graph[current][neighbor])

                if (in_degree[neighbor] == 0) {
                    queue[rear++] = neighbor;
                }
            }
        }
    }

    for (int i = 0; i < N; i++) {
        if (in_degree[i] > 0) {
            return -1; // Graph contains a cycle, scheduling is not possible
        }
    }

    int max_completion_time = 0;
    for (int i = 0; i < N; i++) {
        if (earliest_start_time[i] > max_completion_time) {
            max_completion_time = earliest_start_time[i];
        }
    }

    return max_completion_time;
}

int main() {
    int N, M;
    scanf("%d %d", &N, &M);

    Activity activities[MAX_N];

    for (int i = 0; i < M; i++) {
        scanf("%d %d %d", &activities[i].start, &activities[i].end, &activities[i].duration);
    }

    int result = earliest_completion_time(N, M, activities);

    if (result == -1) {.......