位运算要注意 (对于HDOJ 1547的思考)

今天真坑爹,一个位操作x&1 == 0导致了一种奇妙的错误,也让我反思颇深,乍一看这个式子我们估计大部分人都理解成了(x&1) == 0

其实不然,因为&比==的优先级更低,所以应该是这样运算的x&(1 == 0)

坑吧

搞得我HDOJ 1547wa了一下午,头痛欲裂

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char map[111][111];

int h, w;
int x, y;

int gone[111][111];

int check(int x, int y, char c)
{
	if(x < 1 || x > h || y < 1)
		return 0;
	if((x & 1) == 0 && y > w - 1)  //就是这里错误了
		return 0;
	if((x & 1) == 1 && y > w)
		return 0;
	if(map[x][y] != c)
		return 0;
	if(gone[x][y])
		return 0;
	return 1;

}

int find(int x, int y)
{
	int result = 0;

	if(x == 35 && y == 1)
		printf("");
	gone[x][y] = 1;
	if(check(x + 1, y, map[x][y]))
	{
		result += find(x + 1, y);
	}
	if(check(x - 1, y, map[x][y]))
		result += find(x - 1, y);


	if((x % 2 == 1) && check(x + 1, y - 1, map[x][y]))
	{
		result += find(x + 1, y - 1);
	}
	if((x % 2 == 1) && check(x - 1, y - 1, map[x][y]))
		result += find(x - 1, y - 1);

	if(x % 2 == 0 && check(x + 1, y + 1, map[x][y]))
	{
		result += find(x + 1, y + 1);
	}
	if(x % 2 == 0 && check(x - 1, y + 1, map[x][y]))
		result += find(x - 1, y + 1);


	if(check(x, y - 1, map[x][y]))
		result += find(x, y - 1);
	if(check(x, y + 1, map[x][y]))
		result += find(x, y + 1);

	return result + 1;
}

int check1(int x, int y)
{
	if(x < 1 || x > h || y < 1)
		return 0;
	if((x & 1) == 0 && y > w - 1)
		return 0;
	if((x & 1) == 1 && y > w)
		return 0;
	if(gone[x][y])
		return 0;
	if(map[x][y] == 'E')
		return 0;
	return 1;
}

int go(int x, int y)
{
	if(x == 35 && y == 1)
		printf("");
	gone[x][y] = 1;
	
	if(check1(x + 1, y))
	{
		go(x + 1, y);
	}
	if(check1(x - 1, y))
		go(x - 1, y);


	if((x % 2 == 1) && check1(x + 1, y - 1))
	{
		go(x + 1, y - 1);
	}
	if((x % 2 == 1) && check1(x - 1, y - 1))
		go(x - 1, y - 1);

	if(x % 2 == 0 && check1(x + 1, y + 1))
	{
		go(x + 1, y + 1);
	}
	if(x % 2 == 0 && check1(x - 1, y + 1))
		go(x - 1, y + 1);


	if(check1(x, y - 1))
		go(x, y - 1);
	if(check1(x, y + 1))
		go(x, y + 1);
	return 0;
}

int main()
{
	int i, result, j;
	while(scanf("%d%d%d%d", &h, &w, &x, &y) != EOF)
	{
		for(i = 1; i <= h; i ++)
		{
			scanf("%s", map[i] + 1);
			//for(j = 1; j <= w; j ++)
			//{
			//	map[i][j] = rand() % 3 + 'a';
			//	if(rand() % 26 == 0)
			//		map[i][j] = 'E';
			//}
		}

		result = 0;

		memset(gone, 0, sizeof(gone));
		if((result = find(x, y)) >= 3)
		{
			for(j = 1; j <= w; j ++)
			{
				if(!gone[1][j] && map[1][j] != 'E')
				{
					go(1, j);
				}
			}
			for(i = 1; i <= h; i ++)
				for(j = 1; j <= w - (i % 2 == 0 ? 1 : 0); j ++)
				{
					if(!gone[i][j] && map[i][j] != 'E')
						result ++;
				}
				printf("%d\n", result);
		}
		else
			printf("0\n");
		
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值