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

本文介绍了一个算法,用于解决Bessie从牧场返回谷仓的最短路径问题。给定多个地标和连接它们的牛径,算法确定了从N号地标返回1号地标(谷仓)的最短距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值