题解 P1518 【[USACO2.4]两只塔姆沃斯牛 The Tamworth Two】
老规矩,先审题!
每分钟,农夫和牛可以向前移动或是转弯。
1.如果前方无障碍(地图边沿也是障碍),它们会按照原来的方向前进一步。
2.否则它们会用这一分钟顺时针转 90 度。
终止条件:两者相遇,并且在该分钟末尾。然后计算时间。
分析
1.初始化与读入
根据题意,我们首先可以想到用一个整形变量ans储存分钟数,再用一个二维字符数组map(简称m)储存整张地图。
但是问题来了,map需要开多大呢?首先这是一个边长为10的地图,所以至少要开10 10,但是为了更好的判断越界情况,我们可以开一个12 12的数组,然后把边框全部变为'* ',这样相当于将边框变为了障碍物,判断更加方便。
但是我们要考虑一个问题,我们不能每次移动都遍历一遍数组,太耗时间了,所以我们可以用两个整型数组储存奶牛和农夫的信息(x,y坐标以及方向),每次移动时只需调整信息即可。既然题中说初始方向为正北,我们就可以将初始方向北设为0(初始),顺时针依次将东、南、西设为1,2,3。
char m[12][12];
int f[3],c[3],ans;
for (int i=0;i<=11;i++) m[i][0]='*',m[i][11]='*';
for (int i=1;i<=11;i++) m[0][i]='*',m[11][i]='*';
for (int i=1;i<=10;i++){
for (int j=1;j<=10;j++){
cin>>m[i][j];
if (m[i][j]=='F') f[1]=i,f[2]=j;
if (m[i][j]=='C') c[1]=i,c[2]=j;
}
}
2.移动与转弯
初始环节说完了,下面就迎来了我们的重头戏——移动与转弯。
这一环节其实难度不大,只需设置一个函数处理即可(不设也无所谓),遇到障碍物就拐弯,否则就根据方向移动。
void move(int x,int y,int mi,int h){//x,y为x,y坐标,mi为方向,h为类型:农夫为0,奶牛为1
if (mi==0){
if (m[x-1][y]=='*') if (h==0) f[0]=1; else c[0]=1;
else if (h==0) f[1]--; else c[1]--;
}else if (mi==1){
if (m[x][y+1]=='*') if (h==0) f[0]=2; else c[0]=2;
else if (h==0) f[2]++; else c[2]++;
}else if (mi==2){
if (m[x+1][y]=='*') if (h==0) f[0]=3; else c[0]=3;
else if (h==0) f[1]++; else c[1]++;
}else{
if (m[x][y-1]=='*') if (h==0) f[0]=0; else c[0]=0;
else if (h==0) f[2]--; else c[2]--;
}
}
3.判断是否可以相遇
怎么判断呢?我们可以想到,如果两个物体先后两次从同一个方向走到同一个地点,我们就可以说它们陷入了死循环,但如何判断是否是死循环??这是一个难倒众人的问题。
我们可以通过生成专属值的方法来判断:农夫的x坐标+他的y坐标 10+奶牛的x坐标 100+奶牛的y坐标 1000+农夫的方向 10000+奶牛的方向* 40000(农夫方向最多为4)
bool zt[160005];
tdz=f[1]+f[2]*10+c[1]*100+c[2]*1000+f[0]*10000+c[0]*40000;
if (zt[tdz]){
cout<<0<<endl;
return 0;
}
总代码如下:
#include<bits/stdc++.h>
using namespace std;
char m[12][12];//地图
int f[3],c[3],ans,tdz;//农夫,奶牛,秒数,专属值
bool zt[160005];//记录专属值是否出现
void move(int x,int y,int mi,int h){//移动函数
if (mi==0){
if (m[x-1][y]=='*') if (h==0) f[0]=1; else c[0]=1;
else if (h==0) f[1]--; else c[1]--;
}else if (mi==1){
if (m[x][y+1]=='*') if (h==0) f[0]=2; else c[0]=2;
else if (h==0) f[2]++; else c[2]++;
}else if (mi==2){
if (m[x+1][y]=='*') if (h==0) f[0]=3; else c[0]=3;
else if (h==0) f[1]++; else c[1]++;
}else{
if (m[x][y-1]=='*') if (h==0) f[0]=0; else c[0]=0;
else if (h==0) f[2]--; else c[2]--;
}
}
bool pd(){ //判断循环终止条件:如果奶牛坐标与农夫坐标相等,则他们重叠,返回0,退出循环
if (f[1]==c[1]&&f[2]==c[2]) return 0;
else return 1;
}
int main(){
for (int i=0;i<=11;i++) m[i][0]='*',m[i][11]='*';
for (int i=1;i<=11;i++) m[0][i]='*',m[11][i]='*';
for (int i=1;i<=10;i++){
for (int j=1;j<=10;j++){
cin>>m[i][j];
if (m[i][j]=='F') f[1]=i,f[2]=j;
if (m[i][j]=='C') c[1]=i,c[2]=j;
}
}
while (pd()){//模拟每秒
tdz=f[1]+f[2]*10+c[1]*100+c[2]*1000+f[0]*10000+c[0]*40000;
if (zt[tdz]){//死循环了就输出0并结束程序
cout<<0<<endl;
return 0;
}
zt[tdz]=1;//标记
move(f[1],f[2],f[0],0);
move(c[1],c[2],c[0],1);//依次移动农夫和奶牛
ans++;//记录秒数
}
cout<<ans<<endl;//输出
return 0;
}