1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include<iostream> #include<stdlib.h> #include<stack> #include<queue> using namespace std;
#define MVNum 10//最大顶点数 #define MAXINT 32768//表示极大值
typedef int arcType; typedef char vertexType;
typedef struct MNode{ vertexType vertex[MVNum]; //存储顶点 arcType Arc[MVNum][MVNum]; //邻接矩阵,存储边 int vexnum,arcnum; }GraphNode,*Graph;
int indegree[MVNum]={0}; //记录各个顶点的入度
int Init(Graph &G){ G=(GraphNode *)malloc(sizeof(GraphNode)); G->vexnum=0; G->arcnum=0; if(G) return 1; else cout<<"初始化出错!"<<endl; return 0; }
void FindPos(Graph G,char a,char b,int &pos1,int &pos2){//查找位置 int i=0; pos1=-1;pos2=-1; for(int i=0;i<G->vexnum;i++){ if(G->vertex[i]==a){ pos1=i; continue; } else if(G->vertex[i]==b){ pos2=i; continue; } } }
void CreateDG(Graph G) //创建有向图 { int num=0, //控制输入顶点数 pos1,pos2, //确认顶点位置 i,j; char a, b, ch; //顶点 for(int i=0;i<MVNum;i++){ //初始化 for(int j=0;j<MVNum;j++){ G->Arc[i][j]=0; } }
cout<<"请输入顶点,以#结束"<<endl; cin>>ch; while(ch!='#'&&num<10){ G->vertex[num]=ch; cin>>ch; num++; } G->vexnum=num; cout<<"请输入对应的弧(ab与ba是方向相反的边),以##结束"<<endl; cin>>a>>b; while(a!='#'&&b!='#'){ cout<<a<<"->"<<b<<endl; FindPos(G,a,b,pos1,pos2); cout<<"位置a:"<<pos1<<"位置b:"<<pos2<<endl; if(pos1!=-1&&pos2!=-1){ G->Arc[pos1][pos2]=1; G->arcnum++; indegree[pos2]++; } cin>>a>>b; } }
void topo(Graph G) { stack<int>s; queue<int>q; int i,temp; for(i=0;i<G->vexnum;i++){ if(!indegree[i]) s.push(i); }
while(!s.empty()){ temp=s.top(); q.push(temp); s.pop(); for(i=0;i<G->vexnum;i++){ if(G->Arc[temp][i]){ indegree[i]--; if(indegree[i]==0) s.push(i); } } }
if(q.size()<G->vexnum) printf("该有向图有回路"); else{ while(!q.empty()){ printf("%c ",G->vertex[q.front()]); q.pop(); } } }
void show(Graph G){ for(int i=0;i<G->vexnum;i++){ for(int j=0;j<G->vexnum;j++){ cout<<G->Arc[i][j]<<" "; } cout<<endl; } }
int main(){ Graph G = NULL; Init(G); CreateDG(G); topo(G);
return 0; }
|