2_4 Bessie Come Home(come home)
题目:①、USACO
②、NOCOW
注意:
①、两个农场之间可能多条路径,并且长度不同;
②、无向图;
代码:
#include<stdio.h> #include<assert.h> int main() { FILE *fin,*fout; fin=fopen("comehome.in","r"); fout=fopen("comehome.out","w"); assert(fin); assert(fout); int Arc[58][58]; int pathNum,i,j,k,length; char startPasture,endPasture; fscanf(fin,"%d\n",&pathNum); for(i=0;i<58;i++) for(j=0;j<58;j++) Arc[i][j]=2000000; for(i=0;i<58;i++) Arc[i][i]=0; //get the path and save it in a Array for(i=0;i<pathNum;i++) { fscanf(fin,"%c %c %d\n",&startPasture,&endPasture,&length); if(startPasture!=endPasture) if(Arc[startPasture-65][endPasture-65]>length) { Arc[startPasture-65][endPasture-65]=length; Arc[endPasture-65][startPasture-65]=length; } } //compute the first come cow for(k=0;k<58;k++) for(i=0;i<58;i++) for(j=0;j<58;j++) if(Arc[i][k]+Arc[k][j]<Arc[i][j]) Arc[i][j]=Arc[i][k]+Arc[k][j]; int cow=0,time=2000000; for(i=0;i<25;i++) if(Arc[i][25]<time) { cow=i; time=Arc[i][25]; } else if(Arc[25][i]<time) { cow=i; time=Arc[25][i]; } fprintf(fout,"%c %d\n",cow+65,time); fclose(fin); fclose(fout); return 0; }
总结:
1、使用弗洛伊德算法可以简化过程
for(k=0;k<58;k++)
for(i=0;i<58;i++)
for(j=0;j<58;j++)
if(Arc[i][k]+Arc[k][j]<Arc[i][j]) //如果 i→k→j的路径长度小于i→j的路径长度
Arc[i][j]=Arc[i][k]+Arc[k][j]; //更新

浙公网安备 33010602011771号