POJ北大 2387 (fjutacm 1443)Til the Cows Come Home 最短路径

Problem Description
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.
    SampleInput
    5 5
    1 2 20
    2 3 30
    3 4 20
    4 5 20
    1 5 100
    SampleOutput
    90

题意是给定T条双向边以及对应的权值,让我们求从N回到1所需要走过的最短路程。
这里我用的算法暂时不清楚具体叫什么,算法分析都在代码注释里,先贴代码,以后知道了再回来更新。

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#include <string.h>
using namespace std;
const int MAX=1e3+5;

int N, T;
int dist[MAX][MAX];
bool vis[MAX];
int d[MAX];

int main()
{
  int a, b, c, v, u;
  cin >> T >> N;
  memset(dist, 0x3f, sizeof(dist));
  memset(vis, false, sizeof(vis));
  memset(d, 0x3f, sizeof(d));
  for (int i=0; i<T; i++)
  {
    scanf("%d%d%d", &a, &b, &c);
    if (c<dist[a][b])
    {
      dist[a][b] = dist[b][a] = c;
      if (a==N) d[b] = c;       //把记录起点,到所有点最短路径的一维数组初始化
      else if (b==N) d[a] = c;
    }
  }
  d[N] = 0;       //到自己是0
  while (1)
  {
    v = -1;
    for (int u=1; u<=N; u++)
      if (!vis[u]&&(v==-1||d[u]<d[v]))  // 不断往后找,找到当前没被标记过,且从起
        v = u;                          //点能最快到达的点,以此点为中转点
    if (v==-1) break;                   // 没有没被标记过的点了,就跳出while
    vis[v] = 1;                         // 找到的点标记一下
    for (int u=1; u<=N; u++)            // 找中转点的所有下家,不断更新起点通过中
      d[u] = min(d[u], d[v]+dist[v][u]);//转点到其他所有点的最短路径
  }
  cout << d[1] << endl;
  return 0;
}
发布了19 篇原创文章 · 获赞 0 · 访问量 511

猜你喜欢

转载自blog.csdn.net/qq_43317133/article/details/98203606