USACO section 2.4 Bessie Come Home(最短路)

Bessie Come Home
Kolstad & Burch

It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out which one cow gets to the barn first (the supplied test data will always have exactly one fastest cow).

Between milkings, each cow is located in her own pasture, though some pastures have no cows in them. Each pasture is connected by a path to one or more other pastures (potentially including itself). Sometimes, two (potentially self-same) pastures are connected by more than one path. One or more of the pastures has a path to the barn. Thus, all cows have a path to the barn and they always know the shortest path. Of course, cows can go either direction on a path and they all walk at the same speed.

The pastures are labeled `a'..`z' and `A'..`Y'. One cow is in each pasture labeled with a capital letter. No cow is in a pasture labeled with a lower case letter. The barn's label is `Z'; no cows are in the barn, though.

PROGRAM NAME: comehome

INPUT FORMAT

 

Line 1:Integer P (1 <= P <= 10000) the number of paths that interconnect the pastures (and the barn)
Line 2..P+1:Space separated, two letters and an integer: the names of the interconnected pastures/barn and the distance between them (1 <= distance <= 1000)

SAMPLE INPUT (file comehome.in)

5
A d 6
B d 3
C e 9
d Z 8
e Z 3

OUTPUT FORMAT

A single line containing two items: the capital letter name of the pasture of the cow that arrives first back at the barn, the length of the path followed by that cow.

SAMPLE OUTPUT (file comehome.out)

B 11


思路:直接输入,用数组存,求出所有通路的值,最后扫描一遍,输出答案具体看代码

 

 未修改前4次方

/*
 ID:nealgav1
 LANG:C++
 PROG:comehome
*/
#include<fstream>
#include<cstring>
#include<cstdio>
using namespace std;
ifstream cin("comehome.in");
ofstream cout("comehome.out");
const int mm=11000;
const int oo=1e9;
int dist[210][210];
int dag()
{
  for(int l='A';l<='z';l++)///层数,不加会错
  for(int i='A';i<='z';i++)///连接
  for(int j='A';j<='z';j++)
  { if(i==j)continue;
    for(int k='A';k<='z';k++)
    { if(dist[i][k]&&dist[k][j])
      {
        if(dist[i][j])
        dist[i][j]=dist[j][i]=min(dist[i][j],dist[i][k]+dist[k][j]);
        else dist[i][j]=dist[j][i]=dist[i][k]+dist[k][j];
      }
    }
  }
  int mlen=oo;char ans;
  for(int i='A';i<='Y';i++)
  if(dist[i]['Z'])
  {
    if(dist[i]['Z']<mlen)mlen=dist[i]['Z'],ans=i;
  }
  cout<<ans<<" "<<mlen<<"\n";
  return mlen;
}
int main()
{int m;
 char a,b;int c;
 cin>>m;
 memset(dist,0,sizeof(dist));
 for(int i=0;i<m;i++)
 {
   cin>>a>>b>>c;
   if(dist[a][b]>c||dist[a][b]==0)
   {dist[a][b]=c;dist[b][a]=c;}
 }
 dag();
 ///cout<<dag()<<"\n";
}

修改后3次方算法,其实是上面的算法用的不正确
 

/*
 ID:nealgav1
 LANG:C++
 PROG:comehome
*/
#include<fstream>
#include<cstring>
#include<cstdio>
using namespace std;
ifstream cin("comehome.in");
ofstream cout("comehome.out");
const int mm=11000;
const int oo=1e9;
int dist[210][210];
int dag()
{
  for(int k='A';k<='z';k++)
  for(int i='A';i<='z';i++)///连接
  for(int j='A';j<='z';j++)
  { if(i==j)continue;
     if(dist[i][k]&&dist[k][j])
      {
        if(dist[i][j])
        dist[i][j]=dist[j][i]=min(dist[i][j],dist[i][k]+dist[k][j]);
        else dist[i][j]=dist[j][i]=dist[i][k]+dist[k][j];
      }
  }
  int mlen=oo;char ans;
  for(int i='A';i<='Y';i++)
  if(dist[i]['Z'])
  {
    if(dist[i]['Z']<mlen)mlen=dist[i]['Z'],ans=i;
  }
  cout<<ans<<" "<<mlen<<"\n";
  return mlen;
}
int main()
{int m;
 char a,b;int c;
 cin>>m;
 memset(dist,0,sizeof(dist));
 for(int i=0;i<m;i++)
 {
   cin>>a>>b>>c;
   if(dist[a][b]>c||dist[a][b]==0)
   {dist[a][b]=c;dist[b][a]=c;}
 }
 dag();
 ///cout<<dag()<<"\n";
}


Bessie Come Home
Russ Cox

We use the Floyd-Warshall all pairs shortest path algorithm to calculate the minimum distance between the barn and all other points in the pasture. Then we scan through all the cow-containing pastures looking for the minimum distance.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

#define INF 60000	/* bigger than longest possible path */

int dist[52][52];

int
char2num(char c)
{
    assert(isalpha(c));

    if(isupper(c))
	return c-'A';
    else
	return c-'a'+26;
}

void
main(void)
{
    FILE *fin, *fout;
    int i, j, k, npath, d;
    char a, b;
    int m;

    fin = fopen("comehome.in", "r");
    fout = fopen("comehome.out", "w");
    assert(fin != NULL && fout != NULL);

    for(i=0; i<52; i++)
    for(j=0; j<52; j++)
	dist[i][j] = INF;

    for(i=0; i<26; i++)
	dist[i][i] = 0;

    fscanf(fin, "%d\n", &npath);
    for(i=0; i<npath; i++) {
	fscanf(fin, "%c %c %d\n", &a, &b, &d);
	a = char2num(a);
	b = char2num(b);
	if(dist[a][b] > d)
	    dist[a][b] = dist[b][a] = d;
    }

    /* floyd warshall all pair shortest path */
    for(k=0; k<52; k++)
    for(i=0; i<52; i++)
    for(j=0; j<52; j++)
	if(dist[i][k]+dist[k][j] < dist[i][j])
	    dist[i][j] = dist[i][k]+dist[k][j];

    /* find closest cow */
    m = INF;
    a = '#';
    for(i='A'; i<='Y'; i++) {
	d = dist[char2num(i)][char2num('Z')];
	if(d < m) {
	    m = d;
	    a = i;
	}
    }

    fprintf(fout, "%c %d\n", a, m);
    exit(0);
}

Analysis of and code for Bessie Come Home by Wouter Waalewijn of The Netherlands

When looking at the problem the first thing you can conclude is that for the solution you will need to know all the distances from the pastures to the barn. After calculating them you only have to check all these distances and pick out the nearest pasture with a cow in it, and that's all.

Because the amount of vertices (=pastures+barn) is small, running Floyd/Warshall algorithm will solve the problem easily in time. If you think programming Floyd/Warshall is easier than Dijkstra, just do it. But you can also solve the problem running Dijkstra once, which of course speeds up your program quite a bit. Just initialise the barn as starting point, and the algorithm will find the distances from the barn to all the pastures which is the same as the distances from all the pastures to the barn because the graph is undirected. Using dijkstra for the solution would make far more complex data solvable within time. Here below you can see my implementation of this solution in Pascal. It might look big, but this way of partitioning your program keeps it easy to debug.

Var Dist:Array [1..58] of LongInt;      {Array with distances to barn}
    Vis :Array [1..58] of Boolean;      {Array keeping track which
pastures visited}
    Conn:Array [1..58,1..58] of Word;   {Matrix with length of edges, 0 = no edge}

Procedure Load;
Var TF   :Text;
    X,D,E:Word;
    P1,P2:Char;

Begin
 Assign(TF,'comehome.in');
 Reset(TF);
 Readln(TF,E);                          {Read number of edges}
 For X:=1 to E do
 Begin
  Read(TF,P1);                          {Read both pastures and edge
length}
  Read(TF,P2);
  Read(TF,P2);      {Add edge in matrix if no edge between P1 and P2 yet or}
  Readln(TF,D);     {this edge is shorter than the shortest till now}
  If (Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]=0) or
     (Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]>D) then
  Begin
   Conn[Ord(P1)-Ord('A')+1,Ord(P2)-Ord('A')+1]:=D;
   Conn[Ord(P2)-Ord('A')+1,Ord(P1)-Ord('A')+1]:=D;
  End;
 End;
 Close(TF);
 For X:=1 to 58 do
  Dist[X]:=2147483647;                  {Set all distances to infinity}
 Dist[Ord('Z')-Ord('A')+1]:=0;          {Set distance from barn to barn to 0}
End;

Procedure Solve;
Var X,P,D:LongInt;                      {P = pasture and D = distance}

Begin
 Repeat
  P:=0;
  D:=2147483647;
  For X:=1 to 58 do                     {Find nearest pasture not
visited yet}
   If Not Vis[X] and (Dist[X]<D) then
   Begin
    P:=X;
    D:=Dist[X];
   End;
  If (P<>0) then
  Begin
   Vis[P]:=True;                        {If there is one mark it
visited}
   For X:=1 to 58 do                    {And update all distances}
    If (Conn[P,X]<>0) and (Dist[X]>Dist[P]+Conn[P,X]) then
     Dist[X]:=Dist[P]+Conn[P,X];
  End;
 Until (P=0);                {Until no reachable and unvisited pastures
left}
End;

Procedure Save;
Var TF  :Text;
    X,BD:LongInt;                       {BD = best distance}
    BP  :Char;                          {BP = best pasture}

Begin
 BD:=2147483647;
 For X:=1 to 25 do                      {Find neares pasture}
  If (Dist[X]<BD) then
  Begin
   BD:=Dist[X];
   BP:=Chr(Ord('A')+X-1);
  End;
 Assign(TF,'comehome.out');
 Rewrite(TF);
 Writeln(TF,BP,' ',BD);                 {Write outcome to disk}
 Close(TF);
End;

Begin
 Load;
 Solve;
 Save;
End.

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值