Til the Cows Come Home POJ - 2387 (最短路 裸题)

Til the Cows Come Home POJ - 2387

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.

Examples

Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90




题意:

有权无向图, 给出M条路, 2点可能会有多条路, 求从1到N的最短路

题解:

判断一下取最小权值的路就好了, 直接套模板

经验小结:


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const int inf = 1<<30;
const LL maxn = 1010;

int V, E, cost[maxn][maxn];
int d[maxn];
bool used[maxn];
typedef pair<int, int> P;
int dijkstra(int s){
    //求得从s出发到达各点的最短路径
    ms(used, 0);
    fill(d, d+maxn, inf);
    priority_queue<P, vector<P>, greater<P> > q;
    q.push(P(d[s]=0, s));
    while(!q.empty()){
        P cur = q.top();
        q.pop();
        if(used[cur.second]) continue;
        used[cur.second] = true;
	      //遍历和cur.second相邻的所有点并更新距离
        for(int i = 1; i <= V; i++)
            if(d[i] > d[cur.second]+cost[cur.second][i]){
                d[i] = d[cur.second]+cost[cur.second][i];
                q.push(P(d[i], i));
            }
    }
    return d[V];
}

int main()
{
    fill(cost[0], cost[0]+maxn*maxn, inf);
    cin >> E >> V;
    int u, v, t;
    while(E--){
        cin >> u >> v >> t;
        cost[u][v] = cost[v][u] = min(cost[u][v], t);
    }
    cout << dijkstra(1) << endl;

	return 0;
}

你可能感兴趣的:(思维)