给我一段拓补排序模板c++
时间: 2023-06-03 10:04:29 浏览: 88
以下是一个常见的拓扑排序模板示例,使用C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXN 1000
struct Graph {
int vn;
int **e;
};
int vis[MAXN + 1];
int queue[MAXN + 1];
int head, tail;
void init_graph(struct Graph *g, int vn) {
g->vn = vn;
g->e = (int **) malloc(sizeof(int *) * (vn + 1));
for (int i = 0; i <= vn; ++i) {
g->e[i] = (int *) malloc(sizeof(int) * (vn + 1));
for (int j = 0; j <= vn; ++j) {
g->e[i][j] = 0;
}
}
}
void add_edge(struct Graph *g, int u, int v) {
g->e[u][v] = 1;
}
int topological_sort(struct Graph *g, int *result) {
int cnt = 0;
head = tail = 0;
for (int i = 1; i <= g->vn; ++i) {
int indeg = 0;
for (int j = 1; j <= g->vn; ++j) {
if (g->e[j][i] > 0) indeg++;
}
if (indeg == 0) {
queue[tail++] = i;
}
}
while (head != tail) {
int u = queue[head++];
result[cnt++] = u;
for (int v = 1; v <= g->vn; ++v) {
if (g->e[u][v] > 0) {
g->e[u][v] = 0;
int indeg = 0;
for (int j = 1; j <= g->vn; ++j) {
if (g->e[j][v] > 0) indeg++;
}
if (indeg == 0) {
queue[tail++] = v;
}
}
}
}
return cnt == g->vn;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
struct Graph *g = (struct Graph *) malloc(sizeof(struct Graph));
init_graph(g, n);
for (int i = 0; i < m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
add_edge(g, u, v);
}
int *result = (int *) malloc(sizeof(int) * (n + 1));
if (topological_sort(g, result)) {
for (int i = 0; i < n; ++i) {
printf("%d ", result[i]);
}
printf("\n");
} else {
printf("There is a cycle in the graph.\n");
}
return 0;
}
```
这是一个简单的拓扑排序算法实现,用于解决有向无环图中的线性排序问题。其中,通过读入邻接矩阵来构建图,然后进行拓扑排序,最后输出排序结果或报告图中存在环路。
阅读全文