http://poj.org/problem?id=2632
模拟算法:将整个过程完完整整的走一遍。题目怎么叙述的,程序就怎么运行。所以模拟题对算法设计的要求不高,但是需要大家选择最适当的数据结构来进行模拟,模拟题一般都很繁琐,所以信心和精心是必不可少的。
本题注意点挺多的,变量也很多,稍不注意就会错~~也算是一道比较让人头疼的模拟题了。
#include <stdio.h>
#include <string.h>
int array[101][101];
int a,b;
int xf[4]={-1,0,1,0};
int yf[4]={0,1,0,-1};
struct Robot//自定义数据结构
{
int x,y,d;
}robot[101];//every robot's current position and direction
int forward(int s,int t)//< robot #> < repeat>
{
int x,y,i;
int d = robot[s].d;//取出当前方向
x=robot[s].x;
y=robot[s].y;//取出当前位置
array[x][y]=0;//更新array[][]
for(i=0;i<t;i++)
{
x = x + xf[d];
y = y + yf[d];
if(x<1 || x>a || y<1 || y>b)
{
printf("Robot %d crashes into the wall\n",s);
return 1;
}
if(array[x][y])
{
printf("Robot %d crashes into robot %d\n",s,array[x][y]);
return 1;
}
}
robot[s].x=x;//更新当前所在位置
robot[s].y=y;
array[x][y]=s;//更新array[][]
return 0;
}
int action(int s,char dir,int t)//instruction:< robot #> < action> < repeat>
{
//对于'F'指令,需判断前进是否出界和前进的位置是否已有机器人
//对于'L'和'R'转向指令,只需修改机器人的方向值,注意同一方向转四次等于没转
switch (dir)
{
case 'F':return forward(s,t);
case 'L':robot[s].d=(robot[s].d-t%4+4)%4;break;
case 'R':robot[s].d=(robot[s].d+t%4)%4;break;
}
return 0;
}
int main()
{
int k,n,m,xi,yi,i,j,s,t;
int f=0;
char dir;
scanf("%d",&k);//test numbers
for(i=0;i<k;i++)
{
memset(array,0,sizeof(array));
memset(robot,0,sizeof(robot));
scanf("%d %d",&a,&b);// the size of the warehouse in meters
scanf("%d %d",&n,&m);//the numbers of robots and instructions respectively
for(j=0;j<n;j++)//n个机器人
{
scanf("%d %d %c",&xi,&yi,&dir);//the starting position and direction of each robot
array[xi][yi]=j+1;//array[xi][yj]代表(xi,yj)位置处的robot编号,没有则为0
robot[j+1].x=xi;
robot[j+1].y=yi;//init current position
switch(dir)//init current direction
{
case 'W':robot[j+1].d=0;break;
case 'N':robot[j+1].d=1;break;
case 'E':robot[j+1].d=2;break;
case 'S':robot[j+1].d=3;break;
default:robot[j+1].d=-1;
}
}
f=0;
for(j=0;j<m;j++)//m条指令
{
scanf("%d %c %d",&s,&dir,&t);//instruction:< robot #> < action> < repeat>
if(f==0)
{
f=action(s,dir,t);//action只有两种可能,发生碰撞返回1,无碰撞返回0
}
}
if(f==0)
printf("OK\n");
}
return 0;
}