#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
typedef struct p{
int w;
int data;
struct p*next;
}bian;
typedef struct{
char data;
int in;
bian *first;
}dian;
typedef struct{
dian data[30];
int d,b;
}ljb;
typedef struct s{
int data;
struct s*next ;
}node,*stack;
void creat(ljb &G);
void disp(ljb G);
void top(ljb G);
void inits(stack &S);
void pushs(stack &S,int e);
void pops(stack &S,int &e);
int emptys(stack S);
void inits(stack &S){
S=NULL;
}
void pushs(stack &S,int e){
stack p;
p=new node;
p->data=e;
p->next=S;
S=p;
}
void pops(stack &S,int &e){
stack p;
p=S;
S=p->next;
e=p->data;
delete p;
}
int emptys(stack S){
if(S==NULL)return 1;
else return 0;
}
void creat(ljb &G){
int i,j,k,w;
bian *s;
printf("顶点数和边数:\n");
scanf("%d %d",&G.d,&G.b);
fflush(stdin);
for(i=0;i<G.d;i++){
printf("请输入第%d个顶点的数据:",i+1);
scanf("%c",&G.data[i].data);
fflush(stdin);
G.data[i].in=0;
G.data[i].first=NULL;
}
for(k=0;k<G.b;k++){
printf("请输入第%d个边的数据",k+1);
scanf("%d %d %d",&i,&j,&w);
fflush(stdin);
G.data[j-1].in++;
s=new bian;
s->w=w;
s->data=j-1;
s->next=G.data[i-1].first;
G.data[i-1].first=s;
}
}
void disp(ljb G){
int i;
bian *p;
for(i=0;i<G.d;i++){
printf("%d ",G.data[i].in);
printf("%5c",G.data[i].data);
p=G.data[i].first;
while(p){
printf("->%d %d",p->data,p->w);
p=p->next;
}
printf("\n");
}
}
void top(ljb G){
bian *p;
stack S;
inits(S);
int i,j,k,count=0;
for(i=0;i<G.d;i++)
if(G.data[i].in==0)pushs(S,i);
while(!emptys(S)){
pops(S,k);
p=G.data[k].first;
printf("%c ",G.data[k].data);
count++;
while(p){
j=p->data;
G.data[j].in--;
if(G.data[j].in==0){
pushs(S,j);
}
p=p->next;
}
}
if(count<G.d)printf("出现回路");
}
void main(){
ljb G;
creat(G);
disp(G);
printf("拓扑排序:\n");
top(G);
}
拓扑排序(图)
最新推荐文章于 2023-11-23 17:14:20 发布
