【模拟法】POJ2632
思路
模拟法,其实狠简单的,不过我们要注意的是,如何减少代码长度
我们的做法是:1. 尽量使用全局变量 2.发掘数字之间的联系
代码
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int directions[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//NESW
struct robot
{
int x;
int y;
int direct;
};
struct instruct
{
int index_rob;
int ins;
int num_repeat;
};
int num_case,max_x,max_y,num_robot,num_ins;
vector<robot> Robots;
vector<instruct> Instructs;
pair<int,int> visted[105][105];
bool work(instruct & i)
{
robot & aim=Robots[i.index_rob-1];
if(i.ins==0)
{//forward
visted[aim.x][aim.y].second=0;
for(int cnt=0;cnt<i.num_repeat;cnt++)
{
aim.x+=directions[aim.direct][0];
aim.y+=directions[aim.direct][1];
if(visted[aim.x][aim.y].second==1)
{
cout<<"Robot "<<i.index_rob<<" crashes into robot "<<visted[aim.x][aim.y].first+1<<endl;
return false;
}
if(aim.x<1 || aim.x>max_x || aim.y<1 || aim.y>max_y)
{
cout<<"Robot "<<i.index_rob<<" crashes into the wall"<<endl;
return false;
}
}
visted[aim.x][aim.y].first=i.index_rob-1;
visted[aim.x][aim.y].second=1;
return true;
}
else
{
//rotate
if(i.ins==1)
aim.direct=(aim.direct+i.num_repeat)%4;
else
aim.direct=(aim.direct+3*i.num_repeat)%4;
return true;
}
}
int main()
{
cin>>num_case;
while(num_case--)
{
for(int i=0;i<105;i++)
for(int j=0;j<105;j++)
visted[i][j].second=0;
Robots.clear();
Instructs.clear();
cin>>max_x>>max_y>>num_robot>>num_ins;
for(int i=0;i<num_robot;i++)
{
robot temp;
cin>>temp.x>>temp.y;
visted[temp.x][temp.y].first=i;
visted[temp.x][temp.y].second=1;
char ch;
cin>>ch;
if(ch=='N')
temp.direct=0;
else if(ch=='E')
temp.direct=1;
else if(ch=='S')
temp.direct=2;
else if(ch=='W')
temp.direct=3;
Robots.push_back(temp);
}
for(int i=0;i<num_ins;i++)
{
instruct temp;
cin>>temp.index_rob;
char ch;
cin>>ch;
if(ch=='L')
temp.ins=-1;
else if(ch=='R')
temp.ins=1;
else if(ch=='F')
temp.ins=0;
cin>>temp.num_repeat;
Instructs.push_back(temp);
}
for(int i=0;i<num_ins;i++)
{
if(!work(Instructs[i]))
{
goto end;
}
}
cout<<"OK"<<endl;
end:;
}
}