分支界限法实现单源最短路径

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
//黑科技最小堆实现方法
/*
priority_queue <int> q;
int main() {
    //priority_queue comp() <int> q;
    srand(time(0));
    for (int i = 0;  ; ++i) {
        int n =rand()%10;
        q.push(-1 * n);
        cout << n <<" ";
        if(i>10)break;
    }
    cout <<endl<<"dui"<<endl;
    while (!q.empty()){
        cout << -1 * q.top() <<" ";
        q.pop();
    }
    return 0;
}
 */
struct Node{
    int i;//顶点编号
    int length;//当前路长
    friend bool operator<(Node a, Node b) {//不加friend 就会出错
        return a.length > b.length;//极小堆,默认情况是极大堆.
    }
};
priority_queue < Node > q;
int c[10][10];//图的临街矩阵
int n;
const  int INF = 1 << 30;
int dist[10];
int pre[10];
void graphShortestPath(int v){
    Node E;
    E.i = v;
    E.length = 0;
    dist[v] = 0;
    q.push(E);//一开始没把初始点放进去,导致直接把第二个点pop掉了,没经过第二个点松弛边,所以一直出错.
    while (1){
        for (int j = 1; j <= n; ++j) {
            if ( (c[E.i][j] < INF ) && (E.length + c[E.i][j] < dist[j]) ){
                dist[j] = c[E.i][j] + E.length;
                pre[j] = E.i;
                Node temp;
                temp.i = j;//此处一开始没有及时更新
                temp.length = dist[j];
                //cout << "temp=" << temp.i <<" "<< endl;
                q.push(temp);
            }
        }
//        try {
//            q.pop();
//        }
//        catch (...) { break;}
        if (q.empty())break;
        q.pop();
        E = q.top();
        //cout << "q.top=" << q.top().i <<" ";
    }
}
int main(){
    int m;
    //cin >> n >> m;
    n = 6;
    m = 9;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (i == j) c[i][j] = 0;
            else c[i][j] = INF;
        }
    }
    for (int k = 1; k <= m; ++k) {
        int t1,t2,t3;
        cin >> t1 >> t2 >>t3;
        c[t1][t2] = t3;
    }
    for (int l = 0; l < 10; ++l) {
        dist[l] = INF;
        pre[l] = 0;
    }
    graphShortestPath(1);
    for (int i1 = 1; i1 <= n; ++i1) {
        cout << dist[i1] <<" " ;
    }
    return 0;
}
/*测试数据:
1 2 1
1 3 12
2 3 9
2 4 3
3 5 5
4 3 4
4 5 13
4 6 15
5 6 4
运行结果:
0 1 8 4 13 17
*/

 //测试ppriority_queue
/*
int main(){
    Node temp1,temp2;
    temp1.i=1;
    temp1.length=11;
    temp2.i = 2;
    temp2.length = 22;
    q.push(temp1);
    q.push(temp2);
    cout << q.top().i <<endl;

}*/
    原文作者:分支限界法
    原文地址: https://blog.csdn.net/gavinloverqq/article/details/51376362
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞