拓扑排序

 1 #include <cstdlib>
 2 #include <iostream>
 3 #include <string.h>
 4 using namespace std;
 5 struct graph{
 6        char map[500][20];
 7        long data[500][500];
 8        long vexnum,arcnum;
 9        };
10        
11 long d[500];//d[500]为度
12 long mount=0,p[500];//p[500]存储排序后的信息;
13 
14 
15  
16 long find_number(char a[],graph &Mgraph) 
17 {long long i;
18 for(i=0;i<mount;i++)
19 {if(strcmp(Mgraph.map[i],a)==0)
20 return i;
21 }
22 if(i==mount)
23 {strcpy(Mgraph.map[mount],a);mount++;return mount-1;}
24 }
25           
26           
27           
28 long topsort(graph Mgraph) 
29 {long f1,i,k=0,j=0;
30 long n=Mgraph.vexnum;
31 while(1)
32 {
33   for(i=0;((i<n)&&(d[i]!=0));i++);
34   if(i==n)
35   return 0;
36   for(f1=i,i++;i<n;i++)
37   {if(d[i]==0) 
38    if(strcmp(Mgraph.map[i],Mgraph.map[f1])<0) 
39     f1=i;
40   }
41                
42                p[k++]=f1;if(k==n) return 1;
43                d[f1]=-1;
44                for(i=0;i<n;i++)
45                {d[i]-=Mgraph.data[f1][i];}
46 }
47 }
48           
49 long  input(graph &Mgraph)
50 {long n,m,i,j,k,f1,f2;char a[20],b[20];
51 
52 printf("%15s","");cout<<"请输入图的顶点数";
53 
54 cin>>n;Mgraph.vexnum=n;
55 printf("%15s","");cout<<"请输入图的边数";
56 cin>>m;Mgraph.arcnum=m;
57  mount=0; for(i=0;i<500;i++)
58  strcpy(Mgraph.map[i],"");
59  memset(Mgraph.data,0,sizeof(Mgraph.data));
60  memset(d,0,sizeof(d));
61  memset(p,0,sizeof(p));   
62  printf("%15s","");cout<<"请按提示输入相邻的顶点"<<endl;
63        
64  for(i=1;i<=m;i++)
65  { printf("%15s","");cout<<"起点:";cin>>a;
66    printf("%15s","");cout<<"终点:";cin>>b;
67   f1=find_number(a,Mgraph);f2=find_number(b,Mgraph);
68   if(Mgraph.data[f1][f2]==0)//防止平行边 
69   {Mgraph.data[f1][f2]=1;d[f2]+=1;}
70  }
71 return n;
72 }  
73           
74 
75 int main(int argc, char *argv[])
76 {long n,i;
77 graph Mgraph;
78  n=input(Mgraph);
79  int k=topsort(Mgraph);
80  system("cls");
81  if(!k) 
82  {printf("%15s","");cout<<"impossible"<<endl;}
83  else
84  {printf("%15s","");cout<<"排序结果为"<<endl; 
85   for(i=0;i<n;i++)
86   {printf("%28s","");cout<<Mgraph.map[p[i]]<<endl;}
87   
88  }
89  system("PAUSE");
90 return EXIT_SUCCESS;
91 }
92 
93  
posted @ 2012-05-30 21:59  cseriscser  阅读(161)  评论(0编辑  收藏  举报