求以邻接矩阵存储的有向无环图中的最长路径

来源:互联网 发布:在淘宝上开店费用 编辑:程序博客网 时间:2024/05/16 03:22
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_QueueStatus 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)

原创粉丝点击