OpenJudge:特殊密碼鎖

總時間限制: 1000ms 內存限制: 1024kB

描述

有一種特殊的二進制密碼鎖,由n個相連的按鈕組成(n<30),按鈕有凹/凸兩種狀態,用手按按鈕會改變其狀態。

然而讓人頭疼的是,當你按一個按鈕時,跟它相鄰的兩個按鈕狀態也會反轉。當然,如果你按的是最左或者最右邊的按鈕,該按鈕只會影響到跟它相鄰的一個按鈕。

當前密碼鎖狀態已知,需要解決的問題是,你至少需要按多少次按鈕,才能將密碼鎖轉變爲所期望的目標狀態。

輸入

兩行,給出兩個由0、1組成的等長字符串,表示當前/目標密碼鎖狀態,其中0代表凹,1代表凸。

輸出

至少需要進行的按按鈕操作次數,如果無法實現轉變,則輸出impossible。

樣例輸入

011
000

樣例輸出

1

#include<iostream>
#include<cstring>
#include<cmath>
#include<bitset>
using namespace std;

int flags(int LEN, int t) { //操作鎖l的第t位
	int f=1<<t; //當前位
	if(t>0) { //左側
		f|=1<<(t-1);
	}
	if(t<LEN-1) { //右側
		f|=1<<(t+1);
	}
	return f;
}

bool ok(int lock, int result, int LEN, int &oper) { //判斷是否可以
//	cout<<"ok() LEN="<<LEN<<",oper="<<bitset<32>(oper)<<endl;
	if(oper&1) { //先操作0位
		lock^=flags(LEN,0);
	}
	for(int t=0; t<LEN-1; t++) { //從低位到高位,依次判斷並操作
		if(((lock>>t)&1)!=((result>>t)&1)) { //不等,要操作t+1位
			oper|=1<<(t+1);
//			cout<<"ok() oper="<<bitset<32>(oper)<<endl;
			lock^=flags(LEN,t+1);
//			cout<<"ok() lock="<<bitset<32>(lock)<<",r="<<bitset<32>(result)<<endl;
		}
	}
	if(lock==result) {
		return true;
	}
	return false;
}

int calcBitNum(int oper) { //計算bit位爲1的個數
//	cout<<"calc() oper="<<bitset<32>(oper)<<endl;
	int n=0;
	for(; oper>0; oper>>=1) {
		if((oper&1)>0) {
			n++;
		}
	}
	return n;
}

int main() {
//	freopen("F:\\aain.txt","r",stdin);
	char lockStr[32],resultStr[32];
	int lockLen,lock,result,i,min,n,oper;
	cin>>lockStr>>resultStr; //輸入字符串
//	cout<<"lockStr="<<lockStr<<",resultStr="<<resultStr<<endl;
	lockLen=strlen(lockStr); //求字符串長度
//	cout<<"lockLen="<<lockLen<<endl;
	for(lock=result=i=0; i<lockLen; i++) {
		lock=(lock<<1)+(lockStr[i]=='0'?0:1); //轉成數值
		result=(result<<1)+(resultStr[i]=='0'?0:1); //轉成數值
	}
//	cout<<"lock="<<bitset<32>(lock)<<",result="<<bitset<32>(result)<<endl;
	for(min=32,oper=0; oper<2; oper+=1) { //考慮低位有兩種情況
		int oper_temp=oper;
		if(ok(lock,result,lockLen,oper_temp)) {//判斷是否可以
			n=calcBitNum(oper_temp);//計算按鍵次數
//			cout<<"n="<<n<<endl;
			if(min>n) { //存在更小的方案
				min=n;
			}
		}
	}
	if(min==32) {
		cout<<"impossible";
	} else {
		cout<<min;
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章