邻接表拓扑排序



测试所用图如下:



#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<cmath>
#include<vector>
#include<set>
#define OK 1
#define ERROR 0
using namespace std;
typedef struct NODE{
int adjvex;
int weight;
NODE *next;
}node;

typedef struct {
int in;
int data;
NODE *first;
}nodeList;

typedef struct {
int num_vex;
int num_edge;
nodeList headvex[100];
}Graph;
void create(Graph *g){
scanf("%d%d",&g->num_vex,&g->num_edge);
int i,j,x,y,z;
for(i=0;i<g->num_vex;i++)
{scanf("%d",&g->headvex[i].data);
g->headvex[i].in=0;
g->headvex[i].first=NULL;
}
//相比普通邻接表,拓扑排序的邻接表只是在每个表头节点多加了一个表示入度的值(即是in)
node *e;
for(i=0;i<g->num_edge;i++){
    scanf("%d%d%d",&x,&y,&z);
    e=new NODE();
    e->weight=z;
    e->adjvex=y;
    g->headvex[y].in++;
    e->next=g->headvex[x].first;
    g->headvex[x].first=e;
}

}
int TopologicalSort(Graph *g){
NODE *e;
int i,j,k,gettop;
int mystack[100];
int top=0;
int Count=0;
//top mystack gettop 用来模拟栈
for(i=0;i<g->num_vex;i++)
{
    if(g->headvex[i].in==0)
    mystack[++top]=i;//遍历邻接表表头节点,将入度为零的结点首先入栈
}
while(top!=0){//如果栈不为空,while循环继续
gettop=mystack[top--];//出栈
printf("%d ",g->headvex[gettop].data);
Count++;
for(e=g->headvex[gettop].first;e;e=e->next)
    {
        g->headvex[e->adjvex].in--;//删去被出栈节点所连的边,即是把与此节点邻接的点的入度减一
        if(g->headvex[e->adjvex].in==0)mystack[++top]=e->adjvex;//把入度为0的点入栈
    }
}
printf("\n");
if(Count<g->num_vex)//如果count小于总结点数,说明不是aov网图
return ERROR;
else return OK;
}
int main(){

int i,j,k;
Graph G;
create(&G);
k=TopologicalSort(&G);

printf("ans:%d\n",k);

return 0;
}
/*
14 20
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0 4 1
0 5 1
0 11 1
1 4 1
1 8 1
1 2 1
2 5 1
2 6 1
2 9 1
3 2 1
3 13 1
4 7 1
5 8 1
5 12 1
6 5 1
8 7 1
9 10 1
9 11 1
10 13 1
12 9 1
*/


测试图转换成邻接表如下:



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值