POJ

来源:互联网 发布:北京java 好找工作吗 编辑:程序博客网 时间:2024/06/08 10:14
Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible.

Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.

Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
Input
* Line 1: Two integers: T and N

* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
Output

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.


题意:这既是一道单源最短路的模板题,求从1点到n点的最短距离。

思路:直接用dijkstra算法来算,这个算法就是每次选取最短的路径的那个点,把它加入进来,从而保证从源点到选取的点的距离都是最短的,用d数组保存。


代码:

#include <cstdio>#include <cmath>#include <iostream>#include <cstring>#include <algorithm>#include <queue>#include <stack>#include <vector>#include <map>#include <numeric>#include <set>#include <string>#include <cctype>#include <sstream>#define INF 0x3f3f3f3f#define lson l, m, rt<<1#define rson m+1, r, rt<<1|1using namespace std;typedef pair<int,int> P;typedef long long LL;const int maxn = 1e3 + 5;const int mod = 1e8 + 7;struct edge{    int to,cost;};int n,t;vector<edge>G[maxn<<1];int d[maxn];void dijk(int s){    priority_queue<P,vector<P>,greater<P> >q;    fill (d+1,d+n+1,INF);    d[s]=0;    q.push(P(0,s));    while (!q.empty()){        P p=q.top();        q.pop();        int v=p.second;        if (d[v]<p.first) continue;        for (int i=0;i<G[v].size();i++){            edge e=G[v][i];            if (d[e.to]>d[v]+e.cost){                d[e.to]=d[v]+e.cost;                q.push(P(d[e.to],e.to));            }        }    }}int main() {    //freopen ("in.txt", "r", stdin);    while (~scanf ("%d%d",&t,&n)){        int u,v,cost;        for (int i=1;i<=n;i++) G[i].clear();        while (t--){            scanf ("%d%d%d",&u,&v,&cost);            G[u].push_back(edge{v,cost});            G[v].push_back(edge{u,cost});        }        dijk(1);        printf ("%d\n",d[n]);    }    return 0;}


原创粉丝点击