演算法導論-22.4-5-用隊列實現拓撲排序

來源:互聯網
上載者:User

題目:

在一個有向無迴路圖G=(V,E)上,執行拓撲排序的另一種方法是重複地尋找一個入度為0的頂點,將該點輸出,並將該頂點及其所有的出邊刪除。解釋如何來實現這一想法,才能使得它的已耗用時間為O(V+E)。如果G中包含迴路的話,這個演算法在運行時會發生什嗎?

 

思考:

初始時,所有入度為0的頂點入隊列

while隊列不為空白,作以下處理:

         取隊列頭結點,並出隊列

         處理以頭結點為起點的所有的邊,將邊的終點的入度-1

         若入度減為0,則入隊列

 

代碼:

#include <iostream>#include <queue>using namespace std;#define N 10//邊結點結構struct Edge{int start;//有向圖的起點int end;//有向圖的終點Edge *next;//指向同一個起點的下一條邊int type;//邊的類型Edge(int s, int e):start(s),end(e),next(NULL){}};//頂點結點結構struct Vertex{int id;Edge *head;//指向以該頂點為起點的下一條邊int degree;Vertex(int i):head(NULL),degree(0),id(i){}};//圖結構struct Graph{Vertex *V[N+1];//N個頂點Graph(){int i;for(i = 1; i <= N; i++)V[i] = new Vertex(i);}~Graph(){int i;for(i = 1; i <= N; i++)delete V[i];}};queue<int> Q;int time = 0;//插入邊void InsertEdge(Graph *G, Edge *E){//如果沒有相同起點的邊if(G->V[E->start]->head == NULL)G->V[E->start]->head =E;//如果有,加入到鏈表中,遞增順序排列,便於查重else{//鏈表的插入,不解釋Edge *e1 = G->V[E->start]->head, *e2 = e1;while(e1 && e1->end < E->end){e2 = e1;e1 = e1->next;}if(e1 && e1->end == E->end)return;if(e1 == e2){E->next = e1;G->V[E->start]->head =E;}else{e2->next = E;E->next = e1;}//插入邊的同時,計下每個頂點的入度G->V[E->end]->degree++;}}//拓撲排序void Topological(Graph *G){//隊列初始化while(!Q.empty())Q.pop();int i;//將所有入度為0的點入隊列for(i = 1; i <= N; i++){if(G->V[i]->degree == 0)Q.push(i);}//隊列不為空白while(!Q.empty()){//隊列首元素int t = Q.front();Q.pop();//輸出cout<<char(t+'l')<<' ';//處理以頭結點為起點的所有的邊Edge *e = G->V[t]->head;while(e){//將邊的終點的入度-1G->V[e->end]->degree--;//若入度減為0,則入隊列if(G->V[e->end]->degree == 0)Q.push(e->end);e = e->next;}}cout<<endl;}int main(){//構造一個空的圖Graph *G = new Graph;Edge *E;//輸入邊int i;char start, end;for(i = 1; i <= 14; i++){cin>>start>>end;E = new Edge(start-'p', end-'p');InsertEdge(G, E);//無向圖,要加兩條邊//E = new Edge(end, start);//InsertEdge(G, E);}//拓撲排序並輸出Topological(G);return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.