1. 程式人生 > >7-9 旅遊規劃 (25 分)(Dijkstra演算法)

7-9 旅遊規劃 (25 分)(Dijkstra演算法)

題意: 

 思路:單源最短路問題,Dijkstra演算法搞定就可以了,因為要找出最便宜的最短路,所以需要在更新最短距離的時候加一個條件(即當最短距離相等的時候,如果該路徑的花費更小,就更新最小花費)就可以了。之前自己學的最短路的水平也就僅限於模板題的水平,現在可以在條件上稍微加一些變化,做了資料結構的作業,順便加深了自己對最短路(Dijkstra)演算法的理解。

題目所給樣例的示意圖(資料放在了程式碼的後邊):

程式碼: 

#include <iostream>
#include <queue>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>
#define INF 0x3f3f3f3f
#define FRE() freopen("in.txt","r",stdin)

using namespace std;
typedef long long ll;
typedef pair<int,int> P;//first是距離,second是點的編號
const int maxn = 1000;
struct Edge{
    int to,c,d;
    Edge(int t,int cost,int dis):to(t),c(cost),d(dis){}
};
vector<Edge> G[maxn];
priority_queue<P, vector<P>, greater<P> > que;
int dist[maxn],cost[maxn];
int n,m,st,en;


void init(){
    int s,e,d,c;
    scanf("%d%d%d%d",&n,&m,&st,&en);
    for(int i = 0; i<m; i++){
        scanf("%d%d%d%d",&s,&e,&d,&c);
        G[s].push_back(Edge(e,c,d));
        G[e].push_back(Edge(s,c,d));
    }
    for(int i = 0; i<n; i++){
        dist[i] = INF;
        cost[i] = INF;
    }
}

int main(){
    //FRE();
    init();
    dist[st] = 0;
    cost[st] = 0;
    que.push(P(0,st));//指的是當前點的最短距離
    while(que.size()){
        P p = que.top();
        que.pop();
        int v = p.second;//當前的點
        if(p.first > dist[v])continue;
        //cout<<"v: "<<v;
        for(int i = 0; i<G[v].size(); i++){
            Edge e = G[v][i];//當最短距離相等的時候而花費更小的時候,更新最短距離的花費
            if((dist[e.to] > dist[v]+e.d)||(dist[e.to] == dist[v]+e.d && cost[e.to] > cost[v]+e.c)){
                dist[e.to] = dist[v]+e.d;
                cost[e.to] = cost[v]+e.c;
                //cout<<" cost: "<<cost[e.to];
                que.push(P(dist[e.to], e.to));
            }
            //cout<<" "<<dist[e.to];
        }
        //cout<<endl;
    }
    printf("%d %d\n",dist[en],cost[en]);
    return 0;
}
/*
樣例輸入:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
樣例輸出:
3 40
*/