您的位置:首页 > 理论基础 > 计算机网络

Aov网络与拓补排序的实现

2014-10-24 23:15 155 查看
测试的节点分布如下:



测试代码如下:
/**
拓补排序的实现,使用邻接链表存储有向图
*/
#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
++;
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;
}


测试结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  拓补排序 AOV