patクラスA1030ダイクストラアルゴリズム、2つのマルチスタンダード処理方法

1.ダイクストラ
は、複数の標準を同時に処理します。

#include <cstdio>
#include <climits>
#include <algorithm>
#include <stack>

using namespace std;

struct edge{
    
    
    int dis, price;
    edge(){
    
    
        dis = 0;
    }
};

const int maxc = 500;
const int INF = INT_MAX;

int N, M, S, D;
edge graph[maxc][maxc];
bool confirmed[maxc]={
    
    };
int di[maxc]; //S到城市i的最短距离
int cost[maxc]; //S到城市i在距离最短条件下,最低cost
int pre[maxc]; //记录路径

void init();
void dijkstra();

int main(){
    
    
    scanf("%d%d%d%d", &N, &M, &S, &D);
    while(M--){
    
    
        int c1, c2, d, c;
        scanf("%d%d%d%d", &c1, &c2, &d, &c);
        graph[c1][c2].dis = graph[c2][c1].dis = d;
        graph[c1][c2].price = graph[c2][c1].price = c;
    }
    init();
    dijkstra();
    stack<int> path;
    int v = D;
    while(v!=S){
    
    
        path.push(v);
        v = pre[v];
    }
    path.push(S);
    while(!path.empty()){
    
    
        printf("%d ", path.top());
        path.pop();
    }
    printf("%d %d", di[D], cost[D]);

    return 0;
}

void init(){
    
    
    fill(di, di+N, INF);
    di[S] = 0;
    cost[S] = 0;
    for(int i=0; i<N; i++) pre[i] = i;
    return;
}

void dijkstra(){
    
    
    for(int k=0; k<N; k++){
    
    
        int city=-1, min_d=INF;
        for(int i=0; i<N; i++){
    
    
            if(!confirmed[i] && di[i]<min_d){
    
    
                city = i;
                min_d = di[i];
            }
        }
        if(city==-1) return;
        confirmed[city] = true;
        for(int i=0; i<N; i++){
    
    
            if(!confirmed[i] && graph[city][i].dis!=0){
    
    
                if(di[city]+graph[city][i].dis<di[i]){
    
    
                    //在第一标准上更优
                    di[i] = di[city]+graph[city][i].dis;
                    cost[i] = cost[city] + graph[city][i].price;
                    pre[i] = city;
                }
                else if(di[city]+graph[city][i].dis==di[i] && cost[city]+graph[city][i].price<cost[i]){
    
    
                    //第一标准相同,第二标准更优
                    cost[i] = cost[city] + graph[city][i].price;
                    pre[i] = city;
                }
            }
        }
    }
    return;
}

2. dijkstra + DFS
は最初に最初の標準のみを考慮し、複数の最短パスを記録します。
次に、深さ優先探索を行って、他の標準でより良いパスを見つけます。

おすすめ

転載: blog.csdn.net/sinat_37517996/article/details/104474261