求以鄰接矩陣存儲的有向無環圖中的最長路徑

typedef struct{
    int last_one;
    int length_of_way;
}NODE;
Status Reclear_Queue(Queue &Q,int* indegree,int N){
    ClearQueue(Q);
    for(i = 0;i < N;i++)
        if(!indegree[i]) EnQueue(Q,i);
    return OK;
}//Reclear_Queue
Status Find_longest_way_DAG(MGraph G){
    //求以鄰接矩陣存儲的有向無環圖中的最長路徑
    NODE way[G.vexnum];
    FindInDegree(G,indegree);//求入度序列
    for(i = 0;i < G.vexnum;i++){//路徑初始化
        way[i].last_one = -1
        if(!indegree[i]) way[i].length_of_way = 0;
        else way[i].length_of_way = -1;
    }//for
    InitQueue(Q);
    int processed = 0;
    while(processed < G.vexnum){//找路
        Reclear_Queue(Q,indegree,G.vexnum);
        int Queuel = QueueLength(Q);
        processed += Queuel;
        for(i = 0;i < Queuel;i++){
            DeQueue(S,start);
            for(j = 0;j < G.vexnum;j++){
                if(G.arcs[start][j]){//這裏的假設是相鄰則爲關聯邊長度,不相鄰則爲0
                    indegree[j]--;
                    if(way[start].length_of_way + G.arcs[start][j] > way[j].length_of_way){
                        way[j].length_of_way = way[start].length_of_way + G.arcs[start][j];
                        way[j].last_one = start;
                    }//if
                }//if
            }//for
        }//for
    }//while
    int longest_one = 0;
    int longest = way[longest_one].length_of_way;
    for(i = 1;i < G.vexnum;i++){//找匯
        if(longest < way[i].length_of_way){
            longest = way[i].length_of_way;
            longest_one = i;
        }//if
    }//for
    InitStack(longest_way);
    while(longest_one > 0){//整路
        Push(longest_way,longest_one);
        longest_one = way[longest_one].last_one;
    }//while
    cout << "最長路徑長度:" << longest << endl;
    cout << "最長路徑:" << endl;
    while(!StackEmpty(longest_way)){
        Pop(longest_way,i);
        cout << i ;
    }//while
    cout << endl;
    return OK;
}//Find_longest_way_DAG
時間複雜度分析:一次重整indegree是O(v),路徑初始化也是O(v),找路:O(v^2),找匯O(v),整路O(v),輸出O(v)
    所以整個算法的複雜度是:O(v^2)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章