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.
【题目分析】
给定一张图,求最短路,毫不犹豫,SPFA搞起。1A
【代码】
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
int inq[40001],en,n,m,h[40001],a,b,c,ne[4000001],to[4000001],w[4000001],dis[40001];
inline void add(int a,int b,int c)
{to[en]=b;ne[en]=h[a];w[en]=c;h[a]=en++;}
inline void spfa()
{
memset(inq,0,sizeof inq);
memset(dis,0x3f,sizeof dis);
dis[n]=0;
queue<int>q;
q.push(n);
inq[n]=1;
while (!q.empty())
{
int x=q.front();q.pop();inq[x]=0;
// cout<<x<<endl;
for (int i=h[x];i>=0;i=ne[i])
{
// cout<<x<<" "<<to[i]<<" "<<w[i]<<endl;
if (dis[to[i]]>dis[x]+w[i])
{
dis[to[i]]=dis[x]+w[i];
if (!inq[to[i]])
{
q.push(to[i]);
inq[to[i]]=1;
}
}
}
}
cout<<dis[1]<<endl;
}
int main()
{
memset(h,-1,sizeof h);
cin>>m>>n;
for (int i=1;i<=m;++i) cin>>a>>b>>c,add(a,b,c),add(b,a,c);
spfa();
}
本文介绍了一种使用SPFA算法解决农场中奶牛Bessie如何从草地快速返回畜舍的问题。通过构建图模型并应用最短路径算法,找到从起点到终点的最短距离。
270

被折叠的 条评论
为什么被折叠?



