枚举——POJ1753

POJ 1753




#include<iostream>
#include<bitset>
#include<queue>

using namespace std;
queue<bitset<16>> state;		//record the state of each situation 
bool flag[65536] = { false };	<span style="white-space:pre">	</span>//in case repeated search
int step[65536] ;

void Initialize()
{
	cout << "Please input a 4*4 rectangle while 'b' represents 'black' "
		<< "and 'w' represents 'white':\n";
	
	char c;
	int i = 0, j = 0;
	bitset<16> temp;
	for (i = 0; i < 4; i++)
	{
		for (j = 0; j < 4; j++)
		{
			cin >> c;
			if ('b' == c)
				temp.set(4 * i + j);
			}
	}
	state.push(temp);
	flag[temp.to_ulong()] = true;

}
bitset<16> Flip(bitset<16> piece, int i)
{

	if (i % 4 != 0)			//not in the first column
		piece.reset(i - 1);
	if ((i + 1) % 4 != 0)	//not in the fourth column
		piece.reset(i + 1);
	if (i > 3)				//not in the first row
		piece.reset(i - 4);
	if (i < 12)				//not in the fourth row
		piece.reset(i + 4);

	return piece;
}
bool breadFirstSearch()
{
	while (!state.empty())
	{
		bitset<16> firstState = state.front();
		state.pop();							//queue.pop() do not return the value of the first item!
		for (int i = 0; i < 16; i++)
		{
			bitset<16> temp = Flip(firstState, i);
			if (firstState.none() || (firstState.count() == 16))
			{
				cout << step[firstState.to_ulong()];
				return true;
			}
			else if(!flag[temp.to_ulong()])
			{
				state.push(temp);
				flag[temp.to_ulong()] = true;
				step[temp.to_ulong()] = step[firstState.to_ulong()] + 1;
			}
		}
	}
	return false;
}
int main()
{
	Initialize();
	if (!breadFirstSearch())
		cout << "Impossible!";
	
	return 0;
}



最后:

1. 2^16=65536 ,如果设置的数组大小为65535,那么

输入:

bbbb

bbbb

bbbb

bbbb

输出则是 溢出的

2. bitset<> 会比^ | &方便使用



3.广度优先遍历使用队列作为基本的数据结构,深度优先算法依赖于(在递归中显示或隐士地使用栈)

4.做ACM..不是为了成为ACMer,只是想对数据结构和算法有一个应用实践

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值