hdu 2209 BFS + 状态压缩

来源:互联网 发布:电脑超频软件 编辑:程序博客网 时间:2024/05/01 19:08

这题BFS是比较简单,但是就是在状态压缩和那个翻牌的操作就蛋疼了。。。。开始的时候暴力。。。华丽丽的超时了。。。。最后看了别人的思路,才恍然大悟。。。。

这题:

   因为翻牌是0变1,1变0,所以可以通过异或来实现,而每一位的翻牌操作,只需要事前把用来异或的数算出来保存就行,如下:

      handle[1] = 3;handle[length] = 3 << ( length - 2 );for( int i = 2; i < length; i++ ){handle[i] = 7 << ( i - 2 );}


 

然后其他的就没什么了。。。。。。。

AC代码如下:

#include <iostream>#include <cstring>#include <string>#include <queue>#include <cstdio>using namespace std;typedef struct{int now;int step;}Node;int mark[1<<20];Node start;int handle[21];int BFS( int length ){queue<Node> q;q.push( start );while( !q.empty() ){Node n = q.front();q.pop();if( n.now == 0 ){return n.step;}for( int i = 1; i <= length; i++ ){Node temp = n;temp.step++;temp.now ^= handle[i];if( mark[temp.now] ){continue;}mark[temp.now] = 1;q.push( temp );}}return -1;}int main(){char s[21];while( scanf( "%s", s ) != EOF ){int length = strlen( s );start.now = 0;start.step = 0;for( int i = 0; i < length; i++ ){start.now = start.now * 2 + s[i] - '0';}handle[1] = 3;handle[length] = 3 << ( length - 2 );for( int i = 2; i < length; i++ ){handle[i] = 7 << ( i - 2 );}memset( mark, 0, sizeof( mark ) );int ans;if( length == 1 ){if( s[0] == '0' ){ans = 0;}else{ans = -1;}}else{ans = BFS( length );}if( ans == -1 ){cout << "NO" << endl;}else{cout << ans << endl;}}return 0;}