您的位置:首页 > 产品设计 > UI/UE

TOJ 3984 I guess the gift is an ipad!

2016-07-11 12:24 489 查看
题目链接:http://acm.tju.edu.cn/toj/showp3984.html

题意:贪食蛇。

一个贪食蛇问题,让我们判断当前状态有没有撞墙以及长度。

很多人这个题是用到STL容器去存储蛇身体的位置,小编觉得没有那个必要,这个问题小编采取的方法是直接存储头的位置和尾巴的位置,具体方法就是在下一个位置什么也没有的时候,头和尾一起动,下一个位置有食物的时候头动尾不动,遇到下一个位置超出范围或者撞到身体,直接判结束,特判头的下一个位置时尾巴的情况。

剩下的就模拟就好了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 25;
int G[maxn][maxn];
char op[105];
int pre[maxn],w,h;
bool check(int x,int y)
{
if(x<1 || x>h || y<1 || y>w) return true;
else return false;
}
int main()
{
int n,x,y;
while(scanf("%d%d%d%d%d", &n,&w,&h,&x,&y) && (n||w||h||x||y))
{
memset(G,0,sizeof(G));
for(int i=0; i<n; i++)
{
int tx,ty;
scanf("%d%d", &tx,&ty);
G[tx][ty] = 2;
}
G[x][y] = 1;
int tx=x,ty=y,flag=0;
scanf("%s", op);
int i;
for(i=0; i<strlen(op); i++)
{
if(op[i] == 'U') x--;
else if(op[i] == 'D') x++;
else if(op[i] == 'L') y--;
else y++;
if(check(x,y))
{
printf("The snake crash itself after %d operations.\n", i+1);
break;
}
else if(G[x][y] == 2)
{
//printf("#1\n");
G[x][y] = 1;
flag++;
}
else if(G[x][y] == 0)
{
//printf("#2\n");
G[x][y]++;
G[tx][ty] = 0;
if(op[i-flag] == 'U') tx--;
else if(op[i-flag] == 'D') tx++;
else if(op[i-flag] == 'L') ty--;
else ty++;
}
else if(G[x][y] == 1 && x==tx&&y==ty)
{
//printf("#3\n");
if(op[i-flag] == 'U') tx--;
else if(op[i-flag] == 'D') tx++;
else if(op[i-flag] == 'L') ty--;
else ty++;
}
else if(G[x][y] == 1)
{
//printf("#4\n");
printf("The snake crash itself after %d operations.\n", i+1);
break;
}
}
if(i == strlen(op)) printf("The snake is %d unit long after A's operation.\n", flag+1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: