1. 程式人生 > >旅遊規劃(25 分)

旅遊規劃(25 分)

最短路的一個題目,不知道自己為什麼用spfa過不去,所以用了dij 自己做了一下優化,這個就是更新結點的時候需要注意一下,更新結點先判斷距離,然後判斷花費,

有了一張自駕旅遊路線圖,你會知道城市間的高速公路長度、以及該公路要收取的過路費。現在需要你寫一個程式,幫助前來諮詢的遊客找一條出發地和目的地之間的最短路徑。如果有若干條路徑都是最短的,那麼需要輸出最便宜的一條路徑。

輸入格式:

輸入說明:輸入資料的第1行給出4個正整數NMSD,其中N2)是城市的個數,順便假設城市的編號為0~(N1);M是高速公路的條數;S是出發地的城市編號;D是目的地的城市編號。隨後的M行中,每行給出一條高速公路的資訊,分別是:城市1、城市2、高速公路長度、收費額,中間用空格分開,數字均為整數且不超過500。輸入保證解的存在。

輸出格式:

在一行裡輸出路徑的長度和收費總額,數字間以空格分隔,輸出結尾不能有多餘空格

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <math.h>
#include <stack>
#include <utility>
#include <string>
#include <sstream>
#include <cstdlib>
#include <set>
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 500 + 10;
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
struct Edge
{
    int to;
    int cost;
    int dis;
    Edge()
    {

    }
    Edge(int a,int b,int c)
    {
        to = a;
        dis = b;
        cost = c;
    }
};
vector<Edge>G[maxn*maxn];
typedef pair<int,int >P;
int d[maxn];
int vis[maxn];
int cost1[maxn];
int n,m,s,e;
void dij(int s)
{
    memset(d,INF,sizeof(d));
    memset(cost1,INF,sizeof(cost1));
    memset(vis,0,sizeof(vis));
    for(int i = 0; i < G[s].size(); i++)
    {
        Edge tmp = G[s][i];
        d[tmp.to] = tmp.dis;
        cost1[tmp.to] = tmp.cost;
    }
    while(1)
    {
        int t = -1;
        for(int i = 0; i < n; i++)
        {
            if(!vis[i] && (t == -1 || (d[t] > d[i]||(d[t] == d[i] && cost1[t] <= cost1[i]))))
                t = i;
        }
        if(t == -1)
            break;
        vis[t] = 1;
        for(int i = 0;i < G[t].size();i++)
        {
            Edge tmp = G[t][i];
            if(d[tmp.to] > d[t] + tmp.dis)
            {
                d[tmp.to] = d[t] + tmp.dis;
                cost1[tmp.to] = cost1[t] + tmp.cost;
            }
            else if(d[tmp.to] == d[t] + tmp.dis)
            {
                if(cost1[tmp.to] >= cost1[t] + tmp.cost)
                {
                    cost1[tmp.to] = cost1[t] + tmp.cost;
                }

            }
        }
    }
    printf("%d %d\n",d[e],cost1[e]);
}
int main()
{
    scanf("%d%d%d%d",&n,&m,&s,&e);
    for(int i = 0; i <= 1000; i++)
        G[i].clear();
    for(int i = 0; i < m; i++)
    {
        int a,b,d,w;
        cin>>a>>b>>d>>w;
        G[a].push_back(Edge(b,d,w));
        G[b].push_back(Edge(a,d,w));
    }
    dij(s);
    return 0;
}