描述
给出一个图的结构,输出其拓扑排序序列,要求在同等条件下,编号小的顶点在前
输入
若干行整数,第一行有2个数,分别为顶点数v和弧数a,接下来有a行,每一行有2个数,分别是该条弧所关联的两个顶点编号
输出
若干个空格隔开的顶点构成的序列(用小写字母)
样例输入
6 8 1 2 1 3 1 4 3 2 3 5 4 5 6 4 6 5
样例输出
v1 v3 v2 v6 v4 v5
刚开始我还以为拓扑排序要求出所有的拓扑排序结果...
完整代码
#include <iostream>
#include <stdlib.h>
#include <stack>
#define VISITED 1
#define UNVISITED 0
#define MAX_SIZE 31767
using namespace std;
int visited[MAX_SIZE] = {UNVISITED};
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
}AreNode;
typedef struct Vnode
{
int in_degree;
AreNode *firstarc;
}VNode;
typedef struct
{
VNode adjlist[MAX_SIZE];
int n, e;
}AdjGraph;
void CreateGraph(AdjGraph *&g, int n, int e)
{
int vex_0, vex_1, i;
g = (AdjGraph*) malloc (sizeof(AdjGraph));
g->n = n;
g->e = e;
for (i = 1; i <= g->n; i++) {
g->adjlist[i].firstarc = NULL;
g->adjlist[i].in_degree = 0;
}
while (e--) {
cin >> vex_0 >> vex_1;
AreNode *p = (AreNode*) malloc (sizeof(AreNode));
p->adjvex = vex_1;
p->nextarc = g->adjlist[vex_0].firstarc;
g->adjlist[vex_0].firstarc = p;
g->adjlist[vex_1].in_degree++;
}
}
AreNode* get_min_nexarc(AdjGraph *g, int adjvex)
{
AreNode *p;
int min;
p = g->adjlist[adjvex].firstarc;
min = MAX_SIZE;
// if (p) min = p->adjvex;
while (p) {
if (visited[p->adjvex] == UNVISITED)
min = min < p->adjvex ? min : p->adjvex;
p = p->nextarc;
}
p = g->adjlist[adjvex].firstarc;
while (p) {
if (p->adjvex == min) break;
p = p->nextarc;
}
return p;
}
AreNode* find_nextarc_max_adjvex(AdjGraph *g, int adjvex)
{
AreNode *p;
p = g->adjlist[adjvex].firstarc;
int max_adjvex = 0;
while (NULL != p) {
if (visited[p->adjvex] == UNVISITED)
max_adjvex = max_adjvex > p->adjvex ? max_adjvex : p->adjvex;
p = p->nextarc;
}
p = g->adjlist[adjvex].firstarc;
while (NULL != p) {
if (p->adjvex == max_adjvex) break;
p = p->nextarc;
}
return p;
}
void TopSort(AdjGraph *g)
{
int i, top, max_adj, n;
AreNode *p;
stack <int> adjvex;
// for (i = 1; i <= g->n; i++)
// if (g->adjlist[i].in_degree == 0 ) adjvex.push(i);
// while (!adjvex.empty()) {
// top = adjvex.top();
// adjvex.pop();
// printf("v%d ",top);
// p = g->adjlist[top].firstarc;
// while (p) {
// i = p->adjvex;
// g->adjlist[i].in_degree--;
// if (g->adjlist[i].in_degree == 0) {
// adjvex.push(i);
// }
// p = p->nextarc;
// }
// }
n = g->n;
while (n--)
{
for (i = 1; i <= g->n; i++)
if (g->adjlist[i].in_degree == 0 && visited[i] == UNVISITED) break;
visited[i] = VISITED;
cout << "v" << i << " ";
p = g->adjlist[i].firstarc;
while (p) {
i = p->adjvex;
g->adjlist[i].in_degree--;
p = p->nextarc;
}
}
}
void DisplayGraph(AdjGraph *g)
{
int i;
AreNode *p;
for (i = 1; i <= g->n; i++) {
p = g->adjlist[i].firstarc;
printf("%3d: ",i);
while (NULL != p) {
printf("%3d ",p->adjvex);
p = p->nextarc;
}
printf("
");
}
}
int main(int argc, char const *argv[])
{
AdjGraph *g;
int v, a;
cin >> v >> a;
CreateGraph(g,v,a);
// DisplayGraph(g);
TopSort(g);
system("pause");
return 0;
}