Aov网络与拓补排序的实现

测试的节点分布如下:

测试代码如下:

/**
拓补排序的实现,使用邻接链表存储有向图
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define MAX 7+1
using namespace std;
struct node
{
    int num;
    struct node *next;
};
struct list
{
    int key;
    struct node *head;
};
struct list List[MAX];
int count[MAX];
void init()
{
    struct node *point,*pre;
    int m,n;
    for(int i=1; i<MAX; i++)
    {
        List[i].key=i;
        List[i].head=NULL;
    }
    freopen("input.txt","r",stdin);
    memset(count,0,sizeof(count));
    while(~scanf("%d%d",&m,&n))
    {
        point = (struct node *)malloc(sizeof(struct node));
        point->num = n;
        point->next = NULL;
        count[n]++;
        pre=List[m].head;
        if(pre!=NULL)
        {
            while(pre->next!=NULL)
            pre=pre->next;
            pre->next=point;
        }
        else
        List[m].head=point;
    }
    return;
}

void AOV()
{
    int stack[MAX],top=-1;//用数组模拟一个栈,top为-1的时候,栈为空
    struct node *current;
    memset(stack,-1,sizeof(stack));
    int i;
    for(i=1; i<MAX; i++)
        if(count[i]==0)
        {
            stack[++top]=i;
        }
    while(top>-1)
    {
        printf("第 %d 个节点\n",stack[top]);
        //拆除节点为stack[top]的所有的相关的边,这里即相邻节点的入度减1;
        current=List[stack[top]].head;
        stack[top--]=-1;
        while(current!=NULL)
        {
            count[current->num]--;
            if(count[current->num]==0)
            {
                stack[++top]=current->num;
            }
            current=current->next;
        }
    }
    return;
}

int main()
{
    init();
    AOV();
    return 0;
}

测试结果如下:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值