一项工程由一组子任务构成,子任务之间有的可以并行执行,有的必须在完成了其他子任务后才能执行。例如,下图表示了一项工程若干子任务之间的先后关系。
输入样例:
在这里给出一组输入。例如:
6,5
C1
C2
C3
C4
C5
C6
0,2
1,2
1,5
2,3
3,4
输出样例:
在这里给出相应的输出。例如:
拓扑序列为:C2 C6 C1 C3 C4 C5
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
自定义队列:
#include <stdio.h>
//#include "conio.h"
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 30
#define VERTEX_MAX 30 /*最大顶点数*/
#define VEX_NUM 10
typedef int Status;
typedef char Vextype[20]; /*顶点类型*/
typedef int ElemType;
typedef struct
{
ElemType elem[MAXSIZE];
int top;
}SeqStack; /*定义顺序栈结构*/
typedef struct node /*边结点定义*/
{
int adjvex; /*邻接点域*/
struct node* next; /*指向下一个边结点的指针域*/
}EdgeNode;
typedef struct vnode /*表头结点定义*/
{
int Indegree; /*顶点入度域*/
Vextype vertex; /*顶点信息*/
EdgeNode* firstedge;
}VertexNode;
typedef struct /*图的邻接表存储*/
{
VertexNode adjlist[VERTEX_MAX];
int n, e; /*顶点数和边数*/
} ALGraph;
void InitStack_Sq(SeqStack& s) /*初始化栈操作*/
{
s.top = -1; //s.top从-1开始,指向实际的栈顶元素
}/*InitStack_sq*/
int Empty_Sq(SeqStack s) /*判栈是否为空*/
{
if (s.top == -1)
return 1;
else
return 0;
}/*Empty_sq*/
Status Push_SeqStack(SeqStack& s, ElemType x)//入栈
{
s.elem[++s.top] = x;
return OK;
}
Status Pop_SeqStack(SeqStack& s, ElemType& y)//出栈
{
if (Empty_Sq(s)) return OVERFLOW; /* 栈空不能出栈 */
else {
y = s.elem[s.top];
s.top--; return OK;
} /* 栈顶元素存入*y,返回 */
}
void CreateALGraph(ALGraph& G) /*创建有向图的邻接表*/
{
int i, v, w;
int Indegree[VERTEX_MAX] = { 0 };
EdgeNode* s;
scanf("%d,%d", &(G.n), &(G.e)); /*输入顶点数n和弧数m*/
for (i = 0; i < G.n; i++)
{
scanf("%s", G.adjlist[i].vertex);
G.adjlist[i].firstedge = NULL;//给每个顶点的firstedge域赋初值
}
for (w = 0; w < G.e; w++) /*建立边表*/
{
scanf("%d,%d", &i, &v);
s = (EdgeNode*)malloc(sizeof(EdgeNode));
s->adjvex = v;
Indegree[v]++; /*统计各顶点的入度*/
s->next = G.adjlist[i].firstedge; /*前插方法*/
G.adjlist[i].firstedge = s;
}
for (i = 0; i < G.n; i++)
G.adjlist[i].Indegree = Indegree[i];
}/*CreateALGraph*/
void topsort(ALGraph& G);
int main()
{
ALGraph g;
CreateALGraph(g);
printf("拓扑序列为:");
topsort(g);
return 0;
}
void topsort(ALGraph& G)
{
int i, v, w;
int cnt = 0;//计数器初始化为0
EdgeNode* ptr;
SeqStack st;
InitStack_Sq(st);
for (i = 0; i < G.n; i++)
{
if (G.adjlist[i].Indegree==0)
Push_SeqStack(st, i);
}
while (!Empty_Sq(st))
{
Pop_SeqStack(st, v);//出栈一次,出栈元素放在v中
printf("%s ", G.adjlist[v].vertex);
++cnt;
ptr = G.adjlist[v].firstedge; //ptr指向第一个边结点
while (ptr != NULL)//只要有边
{
w = ptr->adjvex;
G.adjlist[w].Indegree--;
if (G.adjlist[w].Indegree == 0)
Push_SeqStack(st,w);
ptr = ptr->next;
}
}
if (cnt < G.n)
printf("后续无法输出!\n");
}