本文主要是介绍A - Til the Cows Come Home (dijkstra算法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
推荐Dijkstra算法讲解:http://blog.51cto.com/ahalei/1387799
A - Til the Cows Come Home
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.
* 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.
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
90
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
WR 了好多发,终于过了;
注意: 判题时的数据, 可能会有 重复但用时比之前短的 路段;
列如: 前面有 1 4 5;后面又给了 1 4 2;那肯定需要 舍弃第一条数据,所以要在 输入时 加一个大小 判断;
代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#define INF 99999999
#define MM 1005
int e[MM][MM],dis[MM],book[MM];
int n,t,N1,N2,T,minn,flag;
int main()
{
scanf("%d%d",&t,&n);
for(int i=1; i<=n; i++) // 初始化 路程;
for(int j=1; j<=n; j++)
if(i==j) e[i][j]=0;
else e[i][j]=INF;
for(int i=0; i<t; i++)
{
scanf("%d %d %d",&N1,&N2,&T);
if(e[N1][N2]>T)
e[N1][N2]=e[N2][N1]=T; //路 是双向的;
}
memset(dis,0,sizeof(dis));
for(int i=1; i<=n; i++)
{
dis[i]=e[1][i]; // dijkstra 算法
book[i]=0;
}
book[1]=1;
for(int i=1; i<=n; i++)
{
minn=INF;
for(int j=1; j<=n; j++)
{
if(book[j]==0&&dis[j]<minn)
{
minn=dis[j];
flag=j;
}
}
book[flag]=1;
for(int v=1; v<=n; v++)
{
if(dis[v]>dis[flag]+e[flag][v])
dis[v]=dis[flag]+e[flag][v];
}
}
printf("%d\n",dis[n]);
return 0;
}
这篇关于A - Til the Cows Come Home (dijkstra算法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!