题解 | #【模板】拓扑排序#

【模板】拓扑排序

https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c

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

#define MAX_NODES 200000

struct Node {
    int value;
    struct Node* next;
};

struct Graph {
    struct Node* adjList[MAX_NODES];
    int inDegree[MAX_NODES];
    int numNodes;
};

struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->value = value;
    newNode->next = NULL;
    return newNode;
}

struct Graph* createGraph(int numNodes) {
    struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
    graph->numNodes = numNodes;

    for (int i = 0; i < numNodes; ++i) {
        graph->adjList[i] = NULL;
        graph->inDegree[i] = 0;
    }

    return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {
    struct Node* newNode = createNode(dest);
    newNode->next = graph->adjList[src];
    graph->adjList[src] = newNode;

    graph->inDegree[dest]++;
}

void enqueue(int queue[], int* rear, int node) {
    queue[(*rear)++] = node;
}

int dequeue(int queue[], int* front) {
    return queue[(*front)++];
}

int* topologicalSort(struct Graph* graph) {
    int* result = (int*)malloc(graph->numNodes * sizeof(int));
    int front = 0, rear = 0;
    int queue[MAX_NODES];
    int idx = 0;

    for (int i = 0; i < graph->numNodes; ++i) {
        if (graph->inDegree[i] == 0) {
            enqueue(queue, &rear, i);
        }
    }

    while (front != rear) {
        int currentNode = dequeue(queue, &front);
        result[idx++] = currentNode;

        struct Node* temp = graph->adjList[currentNode];
        while (temp != NULL) {
            int adjNode = temp->value;
            graph->inDegree[adjNode]--;
            if (graph->inDegree[adjNode] == 0) {
                enqueue(queue, &rear, adjNode);
            }
            temp = temp->next;
        }
    }

    if (idx != graph->numNodes) {
        free(result);
        return NULL; // Graph contains cycle
    }

    return result;
}

int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    struct Graph* graph = createGraph(n);

    for (int i = 0; i < m; ++i) {
        int u, v;
        scanf("%d %d", &u, &v);
        addEdge(graph, u - 1, v - 1);
    }

    int* result = topologicalSort(graph);
    if (result == NULL) {
        printf("-1\n");
    } else {
        for (int i = 0; i < n; ++i) {
            if (i == n - 1) {
                printf("%d", result[i] + 1);
            } else {
                printf("%d ", result[i] + 1);
            }
        }
        printf("\n");
        free(result);
    }

    return 0;
}

全部评论

相关推荐

一个菜鸡罢了:哥们,感觉你的简历还是有点问题的,我提几点建议,看看能不能提供一点帮助 1. ”新余学院“别加粗,课程不清楚是否有必要写,感觉版面不如拿来写一下做过的事情,教育经历是你的弱势就尽量少写 2. “干部及社团经历”和“自我评价”删掉 3. 论文后面的“录用”和“小修”啥的都删掉,默认全录用,问了再说,反正小修毕业前肯定能发出来 4. 工作经验和研究成果没有体现你的个人贡献,着重包装一下个人贡献
点赞 评论 收藏
分享
11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务