1. 程式人生 > >【POJ - 2387】Til the Cows Come Home(最短路徑 Dijkstra演算法)

【POJ - 2387】Til the Cows Come Home(最短路徑 Dijkstra演算法)

Til the Cows Come Home

大奶牛很熱愛加班,他和朋友在凌晨一點吃完海底撈後又一個人回公司加班,為了多加班他希望可以找最短的距離回到公司。
深圳市裡有N個(2 <= N <= 1000)個公交站,編號分別為1..N。深圳是大城市,公交車整天跑跑跑。公交站1是大奶牛的位置,公司所在的位置是N。所有公交站中共有T (1 <= T <= 2000)條雙向通道。大奶牛對自己的導航能力不太自信,所以一旦開始,他總是沿著一條路線走到底。
大奶牛為了鍛鍊未來的ACMer,決定讓你幫他計算他到公司的最短距離。可以保證存在這樣的路存在。Input第一行:兩個整數:T和N
接下來T行:每一行都用三個空格分隔的整數描述一個軌跡。前兩個整數是路線經過的公交站臺。第三個整數是路徑的長度,範圍為1到100。Output一個整數,表示大奶牛回到公司的最小距離。

Sample Input

5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

Sample Output

90

題目連結

https://vjudge.net/problem/POJ-2387

 

Dijkstra模板題,不說了

 

AC程式碼

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>1
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define Mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define MEM(x,y) memset(x,y,sizeof(x))
#define Maxn 2000+5
#define P pair<int,int>//first最短路徑second頂點編號
using namespace std;
int N,M,X;
struct edge
{
    int to,cost;
    edge(int to,int cost):to(to),cost(cost) {}
};
vector<edge>G[Maxn];//G[i] 從i到G[i].to的距離為cost
int d[Maxn][Maxn];//d[i][j]從i到j的最短距離
void Dijk(int s)
{
    priority_queue<P,vector<P>,greater<P> >q;//按first從小到大出隊
    for(int i=0; i<=M; i++)
        d[s][i]=INF;
    d[s][s]=0;
    q.push(P(0,s));
    while(!q.empty())
    {
        P p=q.top();
        q.pop();
        int v=p.second;//點v
        if(d[s][v]<p.first)
            continue;
        for(int i=0; i<G[v].size(); i++)
        {
            edge e=G[v][i];//列舉與v相鄰的點
            if(d[s][e.to]>d[s][v]+e.cost)
            {
                d[s][e.to]=d[s][v]+e.cost;
                q.push(P(d[s][e.to],e.to));
            }
        }
    }
}
int main()
{
    IOS;
    while(cin>>N>>M)
    {
        for(int i=0; i<N; i++)
        {
            int x,y,z;
            cin>>x>>y>>z;
            G[x].push_back(edge(y,z));
            G[y].push_back(edge(x,z));
        }
        Dijk(1);
        cout<<d[1][M]<<endl;
    }
    return 0;
}

&n