拓撲排序和關鍵路徑

文章出自:http://dsqiu.iteye.com/blog/1689199

拓撲排序和關鍵路徑

 

拓撲排序

拓撲排序最大的用途就是判斷一個有向圖是否有環,當然判斷還有一種方法就是Floyd算法。如果用鄰接表的話拓撲排序的時間複雜度是O(N*E),鄰接矩陣是O(N^2),N表示頂點數,E表示邊數,Floyd時間複雜度是O(N^3)。

 

拓撲排序方法可分爲無前趨的頂點優先的拓撲排序方法和無後繼的頂點優先的拓撲排序方法。

基本拓撲排序算法步驟

1.在有向圖中任選一個沒有前驅的頂點輸出

2.從圖中刪除該頂點和所有以它爲起點的邊

3.重複1和2,直到全部頂點都以輸出

 

拓撲排序的實現(無前趨的頂點優先的拓撲排序方法)

鄰接表實現(使用stack存儲)

C代碼  收藏代碼
  1. /********************************** 
  2.          title:   拓撲排序(鄰接表實現) 
  3.          author:  jay chang 
  4.          date:    2009/07/16 
  5. **********************************/  
  6. #include<iostream>  
  7.   
  8. #define MAXSIZE 99  
  9. #define TRUE 1  
  10. #define FALSE 0  
  11. using namespace std;  
  12. typedef char VertexData;  
  13.    
  14. typedef int AdjType;  
  15.   
  16. typedef struct Stack          //定義棧  
  17. {  
  18.   int data[MAXSIZE+1];  
  19.   int top;  
  20. }Stack;  
  21.   
  22. typedef struct ArcNode       //定義弧結點  
  23. {  
  24.   AdjType adj;  
  25.   ArcNode *nextArc;  
  26. }ArcNode;  
  27.   
  28. typedef struct VertexNode    //定義頂點  
  29. {  
  30.   VertexData vertexData;  
  31.   ArcNode *firstArc;  
  32. }VertexNode;  
  33.   
  34.   
  35. typedef struct AdjMatrix     //定義圖  
  36. {  
  37.   VertexNode vertexNodes[MAXSIZE+1];  
  38.   int verNum,arcNum;  
  39. }AdjMatrix;  
  40.   
  41. //全局變量  
  42. int indegree[MAXSIZE+1]={0};  
  43.   
  44. int LocateGraph(AdjMatrix *g, VertexData vertexData)  
  45. {  
  46.   int iIndex;  
  47.   for(iIndex=1;iIndex<=g->verNum;iIndex++)  
  48.   {  
  49.     if(vertexData==g->vertexNodes[iIndex].vertexData)  
  50.       return iIndex;  
  51.   }  
  52.   return FALSE;  
  53. }  
  54.   
  55. void  CreateGraph(AdjMatrix *g)  
  56. {     
  57.   int iCount,arcStart,arcEnd;char start,end;  
  58.   cout<<"*****************************************"<<endl;  
  59.   cout<<"***       拓撲排序\n";  
  60.   cout<<"***       Author: Jay Chang\n";  
  61.   cout<<"*****************************************"<<endl;  
  62.   cout<<"輸入有向無環圖的頂點,及弧數\n";  
  63.   cin>>g->verNum>>g->arcNum;  
  64.   cout<<"輸入有向無環圖的頂點信息\n";  
  65.   ArcNode *q=NULL;  
  66.   
  67.   for(iCount=1;iCount<=g->verNum;iCount++)  
  68.   {      
  69.        cout<<"輸入第"<<iCount<<"個頂點的信息"<<endl;  
  70.        cin>>g->vertexNodes[iCount].vertexData;  
  71.        g->vertexNodes[iCount].firstArc=NULL;  
  72.   }  
  73.   
  74.   for(iCount=1;iCount<=g->arcNum;iCount++)  
  75.   {  
  76.       cout<<"輸入第"<<iCount<<"條弧的起始與結束的信息"<<endl;  
  77.       cin>>start>>end;  
  78.   
  79.       arcStart=LocateGraph(g,start);  
  80.       arcEnd  =LocateGraph(g,end);  
  81.       
  82.       //添加弧結點  
  83.       q=(ArcNode*)malloc(sizeof(ArcNode));  
  84.       q->adj=arcEnd;  
  85.       q->nextArc=g->vertexNodes[arcStart].firstArc;  
  86.       g->vertexNodes[arcStart].firstArc=q;  
  87.       //對於第arcEnd個頂點的入度值加1  
  88.       indegree[arcEnd]++;  
  89.   }  
  90. }  
  91.   
  92. //判棧空  
  93. int IsEmpty(Stack *stack)  
  94. {  
  95.   return stack->top==-1?TRUE:FALSE;  
  96. }  
  97.   
  98. //初始化棧  
  99. void InitStack(Stack *stack)  
  100. {  
  101.   stack->top=-1;  
  102. }  
  103.   
  104. //出棧  
  105. void Pop(Stack *stack,int *iIndex)  
  106. {  
  107.   *iIndex=stack->data[stack->top--];  
  108. }  
  109.   
  110. //進棧  
  111. void Push(Stack *stack,int value)  
  112. {  
  113.   stack->data[++stack->top]=value;  
  114. }  
  115.   
  116. //拓撲排序  
  117. int Topological(AdjMatrix *g)  
  118. {  
  119.   int iCount,count=0;  
  120.   Stack *stack=(Stack*)malloc(sizeof(Stack));  
  121.   InitStack(stack);  
  122.   ArcNode *p=NULL;  
  123.   
  124.   //對於入度爲0的頂點入棧  
  125.   for(iCount=1;iCount<=g->verNum;iCount++)  
  126.   {  
  127.     if(indegree[iCount]==0){  
  128.       Push(stack,iCount);  
  129.     }  
  130.   }  
  131.   
  132.   cout<<"輸出拓撲序列\n";  
  133.     
  134.   //輸出頂點後,將與該頂點相連的頂點的邊刪除,將與相連頂點的入度減1,如減後爲0,入棧,棧空結束  
  135.   while(!IsEmpty(stack))  
  136.   {  
  137.     Pop(stack,&iCount);  
  138.     cout<<g->vertexNodes[iCount].vertexData<<" ";  
  139.     count++;  
  140.     p=g->vertexNodes[iCount].firstArc;  
  141.     while(p!=NULL)  
  142.     {     
  143.         if(--indegree[p->adj]==0)  
  144.             Push(stack,p->adj);  
  145.         p=p->nextArc;  
  146.     }  
  147.   }//end while  
  148.   
  149.   if(count<g->verNum){  
  150.     cout<<"有迴路"<<endl;  
  151.     return FALSE;  
  152.   }  
  153.   cout<<endl;  
  154. }  
  155.      
  156. int main()  
  157. {  
  158.     AdjMatrix *g=(AdjMatrix*)malloc(sizeof(AdjMatrix));  
  159.     CreateGraph(g);  
  160.     Tuopu(g);  
  161.     return 0;  
  162. }  

 轉自http://jaychang.iteye.com/blog/702073

 

基於DFS實現(無後繼的頂點優先的拓撲排序方法)

 

Cpp代碼  收藏代碼
  1. #include<iostream>  
  2. using namespace std;  
  3. int timef = 0;   
  4. int n ;  
  5. int a[1000][1000];// 圖的鄰接矩陣  
  6. int f[1000];  //完成時間  
  7. int vis[1000];  //1代表 被發現 2代表 已完成  
  8. void DFS(int u)  
  9. {  
  10.        vis[u] = 1;   //記錄發現時刻  
  11.    
  12.        for(int v=1; v<=n; v++) //adj(u)   //O(E)  
  13.               if(a[u][v] && vis[v]==0)  
  14.                 DFS(v);  
  15.        vis[u] = 2;  //記錄完成時刻  
  16.        timef++;  
  17.        f[u] = timef;  
  18. }  
  19. void DFS_main()   //O(V+E)  
  20. {  
  21.        timef = 0;  
  22.        for(int i=1; i<=n; i++)             /// O(V)  
  23.        {  
  24.               if(vis[i] == 0)  
  25.                      DFS(i);  
  26.        }  
  27. }  
  28. void Topological_sort()      //O(V+E)  
  29. {  
  30.        int tp[1000];            ////存放拓撲序列1..V  
  31.        DFS_main();  
  32.    
  33.        for(int i=1; i<=n; i++)   //按finish的時間倒序存放在tp序列tp中  
  34.         tp[n-f[i]+1] = i;  
  35.         
  36.        for(int i=1; i<=n; i++)  
  37.               cout<<tp[i]<<" ";  
  38.        cout<<endl;  
  39. }  
  40. int main()  
  41. {  
  42.        memset(vis,0,sizeof(vis));  
  43.        cin>>n;  
  44.        for(int i=1; i<=n; i++)  
  45.               for(int j=1; j<=n; j++)  
  46.                      cin>>a[i][j];  
  47.         
  48.        Topological_sort();  
  49.        system("pause");  
  50.        return 0;  
  51. }  
  52.    

 轉自http://blog.sina.com.cn/s/blog_6ec5c2d00100szit.html

 

關鍵路徑

 

相關量介紹,設源點v0,匯點vn-1:

ve(i)表示事件vi最早發生的時間,vl(i)表示事件vi最晚發生的時間。

ve(0)=0,按拓撲排序計算ve(i)的值,ve(j)=max{ve(i)+w(i,j)|<i,j>∈E}。

vl(n-1)=ve(n-1),vl(i)按逆拓撲排序進行計算,vl(i)=min{vl(j)-w(i,j)|<i,j>∈E}。

活動<i,j>最早開始時間ee(i)=ve(i);活動<i,j>最晚開始時間el(i,j)=vl(j)-w(i,j),如果el(i,j)=ee(i,j),則活動<i,j>是關鍵活動。

 

關鍵路徑算法的流程

1.以拓撲排序的次序按ve(j)=max{ve(i)+w(i,j)|<i,j>∈E}計算各個頂點(事件)最早發生的時刻

2.以逆拓撲排序的次序按vl(j)=min{ve(i)+w(i,j)|<i,j>∈E}計算各個頂點(事件)最晚發生的時刻

3.計算每個活動<i,j>發生的最早時間ee(i,j)和最晚時間el(i,j),如果滿足ee(i,j)=el(i,j)則是關鍵路徑並輸出。

 

關鍵路徑算法實現

 

 

Cpp代碼  收藏代碼
  1. #include <iostream>    
  2. using namespace std;    
  3. #define MAX 10000000    
  4. #define MAX_VERTEX_NUM 20    
  5. int ve[MAX_VERTEX_NUM];    
  6. /*順序棧的定義*/    
  7. #define Stack_Size 100    
  8. typedef struct sqStack    
  9. {    
  10.        int *elem;    
  11.        int top;    
  12.        int stackSize;//棧數組長度    
  13. }sqStack;    
  14.      
  15.      
  16. /*順序棧的初始化*/    
  17. void initStack_Sq(sqStack &S)    
  18. {    
  19.        S.elem=new int[Stack_Size];    
  20.        S.top=-1;    
  21.        S.stackSize=Stack_Size;    
  22. }    
  23. /*入棧*/    
  24. void push(sqStack &S,int x)    
  25. {    
  26.        if(S.top==Stack_Size-1)    
  27.               cout<<"Stack Overflow!";    
  28.        S.elem[++S.top]=x;    
  29. }    
  30.      
  31. /*出棧*/    
  32. int pop(sqStack &S)    
  33. {    
  34.        int x;    
  35.        if(S.top==-1)    
  36.               cout<<"Stack Empty!";    
  37.        x=S.elem[S.top--];    
  38.        return x;    
  39. }    
  40. typedef struct EdgeNode    
  41. {//邊表結點的定義    
  42.     int adjvex;//存放鄰接點在頂點表中的位置    
  43.     struct EdgeNode * nextedge;//指向下一個邊表結點    
  44.     int weight;    
  45. }EdgeNode;    
  46. typedef struct VexNode    
  47. {//頂點表結點的定義    
  48.     char vex;//存放頂點信息    
  49.     EdgeNode * firstedge;//指向第一個邊表結點    
  50.     int indegree;    
  51. }VexNode;    
  52. typedef struct    
  53. {//頂點表的定義       
  54.     VexNode vexs[MAX_VERTEX_NUM];    
  55.     int vexnum,edgenum;    
  56. }LGraph;    
  57. /*構造有向圖的鄰接表*/    
  58. void CreateDG_AL(LGraph &G,int n,int e)    
  59. {    
  60.     int i,j,k,w;    
  61.     G.vexnum=n;    
  62.     G.edgenum=e;    
  63.     for(i=0;i<n;i++)    
  64.     {    
  65.         cin>>G.vexs[i].vex;    
  66.         G.vexs[i].firstedge=NULL;//初始化爲空    
  67.     }    
  68.     for(k=0;k<e;k++)    
  69.     {    
  70.         EdgeNode *p;    
  71.         cin>>i>>j>>w;    
  72.         p=new EdgeNode;    
  73.         p->adjvex=j;    
  74.         p->weight=w;    
  75.         p->nextedge=G.vexs[i].firstedge;    
  76.         G.vexs[i].firstedge=p;//採用頭插法    
  77.     }    
  78. }    
  79. //拓撲排序並求各頂點事件的最早發生時間及拓撲逆序列    
  80. void TopoSort(LGraph &G,sqStack &T)    
  81. {    
  82.     sqStack S;    
  83.     initStack_Sq(S);    
  84.     EdgeNode *p;    
  85.         
  86.     int count=0;    
  87.     int i;    
  88.     for(i=0;i<G.vexnum;i++)    
  89.         G.vexs[i].indegree=0;//初始化爲0    
  90.     for(i=0;i<G.vexnum;i++)    
  91.     {//計算各個頂點的入度    
  92.         p=G.vexs[i].firstedge;    
  93.         while(p)    
  94.         {    
  95.             G.vexs[p->adjvex].indegree++;    
  96.             p=p->nextedge;    
  97.         }    
  98.     }    
  99.     for(i=0;i<G.vexnum;i++)    
  100.         if(G.vexs[i].indegree==0)    
  101.             push(S,i);//將度爲0的頂點入棧,這裏進棧的是入度爲0的頂點在數組中的位置    
  102.     for(i=0;i<G.vexnum;i++)    
  103.         ve[i]=0;//初始化頂點事件的最早發生時間爲0    
  104.     while(S.top!=-1)    
  105.     {    
  106.         i=pop(S);    
  107.         cout<<G.vexs[i].vex<<" ";//將棧頂的元素出棧且輸出,即將入度爲0的頂點輸出    
  108.         push(T,i);//爲了求得拓撲序列的逆序列,將元素依次進棧就得到了逆序列    
  109.         count++;//計數器加1    
  110.         p=G.vexs[i].firstedge;//讓p指向入度爲0的頂點的第一個邊表結點    
  111.         while(p)    
  112.         {    
  113.             int k;    
  114.             int dut;    
  115.             dut=p->weight;    
  116.             k=p->adjvex;    
  117.             G.vexs[k].indegree--;//將入度爲0的頂點的鄰接點的入度減1    
  118.             if(G.vexs[k].indegree==0)    
  119.                 push(S,k);//度減1後的頂點如果其入度爲0,則將其入棧    
  120.             if(ve[i]+dut>ve[k])    
  121.                 ve[k]=ve[i]+dut;//經過while循環,將頂點事件的所有鄰接點的最早發生時間算出來,    
  122.                                 //並且經過外層的while循環,不斷地更新爲較大的ve[k]值    
  123.             p=p->nextedge;    
  124.         }    
  125.     }    
  126.     cout<<endl;    
  127.     if(count<G.vexnum)    
  128.         cout<<"Network G has citcuits!"<<endl;    
  129. }    
  130. //求關鍵路徑和關鍵活動    
  131. void CriticalPath(LGraph &G)    
  132. {    
  133.     int i,j,k,dut;    
  134.     int ee,el;    
  135.     int vl[MAX_VERTEX_NUM];    
  136.     EdgeNode *p;    
  137.     sqStack T;    
  138.     initStack_Sq(T);    
  139.     TopoSort(G,T);    
  140.     for(i=0;i<G.vexnum;i++)    
  141.         vl[i]=ve[G.vexnum-1];//初始化頂點事件的最遲發生時間爲匯點的最早發生時間    
  142.                             //因爲求最遲發生時間是從匯點向源點開始計算的    
  143.     while(T.top!=-1)    
  144.     {//經過while循環,按堆棧順序求出每個頂點的最遲發生時間    
  145.         for(j=pop(T),p=G.vexs[j].firstedge; p ;p=p->nextedge)    
  146.         {//這裏應該注意for循環的機制:每一次循環都要判斷一次條件,包括第一次    
  147.             k=p->adjvex;    
  148.             dut=p->weight;    
  149.             if(vl[k]-dut<vl[j])    
  150.                 vl[j]=vl[k]-dut;//按堆棧T中事件的順序,將該頂點事件的最遲發生時間經過for循環算出來,    
  151.                                 //注意:經過for循環算出的是一個頂點的最遲發生時間                             
  152.         }    
  153.     }    
  154.     for(i=0;i<G.vexnum;i++)    
  155.     {//依次遍歷每一個活動    
  156.         for(p=G.vexs[i].firstedge;p;p=p->nextedge)    
  157.         {    
  158.             k=p->adjvex;    
  159.             dut=p->weight;    
  160.             ee=ve[i];//求活動的最早開始時間    
  161.             el=vl[k]-dut;//求活動的最遲開始時間    
  162.             if(ee==el)    
  163.             {//若兩者相等,說明這這個活動爲關鍵活動    
  164.                 cout<<"("<<G.vexs[i].vex<<","<<G.vexs[k].vex<<")"<<dut<<" ";    
  165.                 cout<<"ee="<<ee<<","<<"el="<<el<<endl;    
  166.             }    
  167.         }    
  168.     }    
  169. }    
  170. void main()    
  171. {    
  172.     freopen("in.txt","r",stdin);    
  173.     LGraph G;    
  174.     CreateDG_AL(G,9,11);    
  175.     CriticalPath(G);    
  176. }    

轉自http://blog.csdn.net/hackerain/article/details/6054188

  

小結

這篇文章講了有關有向無環圖的兩個應用,最要將能熟悉拓撲排序和關鍵路徑的算法的原理就能加以應用。如果你有任何建議或者批評和補充,請留言指出,不勝感激,更多參考請移步互聯網。


發佈了26 篇原創文章 · 獲贊 79 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章