您的位置:首页 > 其它

26.基于 有向图的邻接表表示 实现 AOV网 的拓扑排序

2014-04-21 22:19 357 查看
////////////////////////////////////////
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
bool e;
fopen_s(&fp, "data.txt", "r");
if (!fp) exit(ERROR);
return;
}
typedef bool Status;
////////////////////////////////////////

/******
file input:
6
1 2
3 4
1 4
3 2
2 5
5 6
4 6
0 0

*******/

////////////////////////////////////////

// 26.基于 有向图的邻接表表示 实现 AOV网 的拓扑排序

typedef struct node
{
int vertex;//在head节点中 vertex表示节点邻接到该点的数量(也就是该点的入度)  也就是该点的出度count,在邻接表中 表示对应结点的标号.
struct node *link;

}Node, *node_ptr, *Head_ptr;

int ver_num;
Head_ptr vertex;

Status InitGraph()
{
int a, b, n;//n个节点   对应  1.......n
fscanf_s(fp, "%d", &n);
ver_num = n;
vertex = (node_ptr)malloc(sizeof(Node)*(n + 1));
if (!vertex) exit(ERROR);
for (int i = 0; i <= n; i++){ vertex[i].vertex = 0; vertex[i].link = NULL; }
while (fscanf_s(fp, "%d %d", &a, &b) && a && b)
{
if (a<1 || a>n || b<1 || b>n)  exit(ERROR);
node_ptr  c;
if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
c->vertex = b;
c->link = vertex[a].link;
vertex[a].link = c;
vertex[b].vertex++;
}
return OK;
}

void Output_node(node_ptr t)
{
printf("----> %d ", t->vertex);
//if (!t->link) putchar(10);
}
void OutputGraph()
{
printf("节点个数为%d :从 1 到 %d\n", ver_num, ver_num);
printf("邻接表表示如下:\n");
int n = ver_num;
for (int i = 1; i <= n; i++)
{
printf("\nnode : %d :  (%d)  ", i, vertex[i].vertex);
node_ptr t = vertex[i].link;
while (t)
{
Output_node(t);
t = t->link;
}
}
printf("\n");
}

queue<int> Q;
int flag = 1;
Status topsort()
{
node_ptr temp;
int *marked = (int *)malloc(sizeof(int)*(ver_num + 1));
if (!marked) return ERROR;
//memset(marked, 0, sizeof(marked));
for (int i = 1; i <= ver_num; i++) marked[i] = 0;
int top = -1, t;
for (int i = 0; i < ver_num; i++)
{
t = 1;
while (t <= ver_num)
{
if (vertex[t].vertex == 0 && !marked[t])
{
top = t; break;
}
t++;
}

//top = t;

if (top == -1) { flag = 0; break; }
Q.push(top); marked[top] = 1;
temp = vertex[top].link;
while (temp)
{
vertex[temp->vertex].vertex--;
temp = temp->link;
}
top = -1;
}

return OK;
}

//by zhaoyang @ 2014.4.21
int main()
{
InitFile();

InitGraph();
OutputGraph();

topsort();
int t;
if (flag){
printf("存在一种拓扑排序为:\n");
while (!Q.empty())
{
t = Q.front(); Q.pop();
printf("----> %d ", t);
}
printf("\n");
}
else printf("存在有向环路,不存在拓扑序\n");

fclose(fp);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: