TOJ 3984 I guess the gift is an ipad!

题目链接: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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值