黑白棋问题——位运算及广度优先

来源:互联网 发布:助创cms众筹破解版 编辑:程序博客网 时间:2024/06/06 06:48

描述

There is a string which consists 0s and 1s only.
Each time you can change one digit, with 0 changed to 1, or 1 changed to 0.
But when you change the digit, the digits on its left and right is changing in the same way.
Please tell me the minimum moves to change the string to 00…000.
If it is impossible please output “NO” in a single line.

输入

In each line there is a string. The length of the string is shorter than 20.

输出

For each string you have to output the minimum number or “NO” in a single line.

样例输入

01
011
101

样例输出

NO
1
2

应该是真正意义上的第一次用位运算来模拟,摸着石头过河的感觉。

题意类黑白棋问题,给一个由01组成的字符串,每次可以改变一个数字(同时两边的数字也会改变),问多少次操作后会得到全0序列。

这道题最大长度为20,也就是说所有情况都可以用1024*1024一下的数字来表示, 而一百万个int 的空间消耗也是可以接受的。

 

流程:

首先将输入字符串转化为数字,入队。

队头出队,如果满足条件,则输出当前操作数。否则将这个数进行位运算。 改变的三位可以用与7(111)异或来得到。因1^1=0,0^1=1. 其他位与0异或,任何数与0异或还是他本身。 例如当前数字二进制表示为101101,当想翻转前三个数字时,得到的数为101101^111000=010101 。这里要注意的是,要单独考虑翻转前两个数与最后两个数的情况,此时应该与3异或。

得到新数后,在flag数组中校验,如果这个数之前未出现过,则入队。

因为之前出现过的情况都不会再入队,故不会有循环出现。当队列为空时,说明翻转不可能完成。

 

代码:

#include<iostream>#include<queue>#include<string>#include<algorithm>using namespace std;bool flag[2000000];class node{public:int ct;int num;};queue<node >Q;int main(){string s;int i,j;while(cin>>s){while(!Q.empty())Q.pop();memset(flag,0,sizeof(flag));int len=s.length();int sum=0;int temp=1;for(i=len-1;i>=0;i--){sum+=temp*(s[i]-'0');temp=temp<<1;}if(sum==0){cout<<0<<endl;continue;}if(sum==1&&len==1){cout<<1<<endl;continue;}if(len==2){if(sum==2||sum==1){cout<<"NO"<<endl;continue;}if(sum==3){cout<<1<<endl;    continue;}}node p,q;p.ct=0;p.num=sum;flag[sum]=1;int suc=0;Q.push(p);while(!Q.empty()){p=Q.front();//cout<<p.num<<endl;Q.pop();if(!p.num){suc=p.ct;break;}sum=p.num^(3<<(len-2));if(!flag[sum]){flag[sum]=1;q.num=sum;q.ct=p.ct+1;Q.push(q);}for(i=0;i<=len-3;i++){sum=p.num^(7<<i);if(!flag[sum]){flag[sum]=1;q.num=sum;q.ct=p.ct+1;Q.push(q);}}sum=p.num^3;if(!flag[sum]){flag[sum]=1;q.num=sum;q.ct=p.ct+1;Q.push(q);}}if(suc==0)cout<<"NO"<<endl;elsecout<<suc<<endl;}}


 

0 0
原创粉丝点击