AOV 模板

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;

#define MAXN 10 // 顶点个数最大值
struct Arcnode
{
    int to;
    Arcnode *next;
};

Arcnode* List[MAXN]; // 每个顶点的边链表表头指针
int count[MAXN]; // 各顶点的入度
char output[200]; // 输出内容
int n, m; // 顶点个数边数

void TopSort()
{
    int i, top = -1;
    int pos = 0; // 写入output数组的位置
    Arcnode* temp;
    bool circle = false; // 是否存在有向环的标志
    for (int i = 0; i < n; i++) // 入度为0的顶点入栈
    {
        if (count[i] == 0)
        {
            count[i] = top;
            top = i;
        }
    }
    for (int i = 0; i < n; i++)
    {
        if (top == -1) // 栈为空存在有向贿赂
        {
            circle = true;break;
        }
        else{
            int j = top; // 栈顶顶点j出栈
            top = count[top]; 
            pos += sprintf(output + pos, "%d ", j + 1);
            temp = List[j];
        // 遍历顶点j的边链表,每条出边的终点的入度减1
while (temp != NULL) { int k = temp->to; if (--count[k] == 0) // 终点入度减至0, 则入栈 { count[k] = top; top = k; } temp = temp->next; }// end of while }// end of else }//end of for if (circle) { printf("Network has a circle "); } else{ int len = strlen(output); output[len-1] = 0; // 去掉最后的空格 printf("%s ", output); } } int main() { freopen("in.txt", "r", stdin); int i, u ,v;  // 循环变量,边的起点和终点 while(1) { scanf("%d%d", &n, &m); // 读入顶点个数, 边数 if (n == 0 && m == 0) break; memset(count, 0, sizeof(count)); memset(List, 0, sizeof(List)); memset(output, 0, sizeof(output)); Arcnode* temp; for (int i = 0; i < m; i++) // 构造边链表 { scanf("%d%d", &u, &v); // 读入边的起点和终点 u--;v--; count[v]++; temp = new Arcnode; temp -> to = v; // 构造邻接表 temp->next = NULL; if (List[u] == NULL) // 此时边链表中没有边结点 { List[u] = temp; } else // 边链表中已经有边节点 { temp->next = List[u]; List[u] = temp; } } TopSort(); for (int i = 0; i < n; i++) // 释放边链表上各边节点所占用的存储空间 { temp = List[i]; while (temp != NULL) { List[i] = temp->next; delete temp; temp = List[i]; } } } return 0; }
原文地址:https://www.cnblogs.com/hulian425/p/12238353.html