POJ Til the Cows Come Home【dijkstra+spfa】
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
*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
Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90
方法一:dijkstra
code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h>
#include<string.h>
#define maxint 999999
int dist[1001];
int c[1001][1001];
void dijkstra(int n,int v)
{
int s[1001];
int i,j,tmp,u,newdist;
memset(s,0,sizeof(s));
for(i=1;i<=n;i++)
dist[i]=c[v][i];
dist[v]=0;
s[v]=1;
for(i=2;i<=n;i++)
{
tmp=maxint;
u=v;
for(j=1;j<=n;j++)
if((!s[j])&&dist[j]<tmp)
{
u=j;
tmp=dist[j];
}
s[u]=1;
for(j=1;j<=n;j++)
if((!s[j])&&c[u][j]<maxint)
{
newdist=dist[u]+c[u][j];
dist[j]=(newdist<dist[j])?newdist:dist[j];
}
}
}
int main()
{
int i,j,p,q,len;
int n,line;
while(scanf("%d%d",&line,&n)!=EOF)
{
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
c[i][j]=(i==j)?0:maxint;
for(i=1;i<=line;i++)
{
scanf("%d%d%d",&p,&q,&len);
if(len<c[p][q])
{
c[p][q]=len;
c[q][p]=len;
}
}
for(i=1;i<=n;i++)
dist[i]=maxint;
dijkstra(n,1);
printf("%d\n",dist[n]);
}
return 0;
}
方法二:spfa 邻接表
code:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h>
#include<string.h>
#define M 1010
struct node //用邻接表不需要考虑重边的问题
{
int v;
int w;
int next;
}e[M<<2];
int n,m=1,T;
int f[M],s[M],Head[M];
int q[M+2],head=0,tail=1;
void AddEdge(int x,int y,int z) //向邻接表添加边
{
e[m].v=y;e[m].w=z;e[m].next=Head[x];Head[x]=m++;
e[m].v=x;e[m].w=z;e[m].next=Head[y];Head[y]=m++;
}
void spfa()
{
int p,x;
s[1]=0;
f[1]=1;
q[0]=1;
while(head!=tail) //队列松弛
{
p=q[head++];
f[p]=0;
head=head%(n+1);
for(x=Head[p];x>0;x=e[x].next)
{
if(e[x].w+s[p]<s[e[x].v]||s[e[x].v]<0)
{
s[e[x].v]=e[x].w+s[p];
if(!f[e[x].v])
{
q[tail++]=e[x].v;
f[e[x].v]=1;
tail=tail%(n+1);
}
}
}
}
}
int main()
{
int x,y,z;
memset(f,0,sizeof(f));
memset(s,-1,sizeof(s));
memset(Head,-1,sizeof(Head));
scanf("%d%d",&T,&n);
while(T--)
{
scanf("%d%d%d",&x,&y,&z);
AddEdge(x,y,z);
}
spfa();
printf("%d\n",s[n]);
return 0;
}