您的位置:首页 > 其它

算法基础_熄灯问题

2017-12-09 20:46 190 查看

提示:

用二进制数进行枚举:讲一个int类型的数从0循环到2^k-1,k是所需用到的比特个数(见eg.2);

用特定字符串等的首字母加switch_case判断输入(见eg.1);

eg.1

#include<iostream>
#include<cstring>
using namespace std;
char Left[3][7];
char Right[3][7];
char result[3][7];
bool IsFake(char c,bool light);

int main()
{
int t;
cin>>t;
while(t--){
for(int i = 0;i<3;++i) cin>>Left[i]>>Right[i]>>result[i];
for(char c='A';c<='L';c++){
if(IsFake(c,true)){
cout<< c <<" is the couterfeit coin and it is light."<<endl;
break;
}
else if(IsFake(c,false)){
cout<<c<<" is the counterfeiter coin and it is heacy."<<endl;
break;
}
}
}
return 0;
}

bool IsFake(char c,bool light)
{
for(int i=0;i<3;i++){
char *pLeft,*pRight;
if(light){
pLeft = Left[i];
pRight = Right[i];
}
else{
pLeft = Right[i];
pRight = Left[i];
}

switch(result[i][0]){
case 'u':
if(strchr(pRight,c)==NULL)
return false;
break;
case 'e':
if(strchr(pLeft,c) || strchr(pRight,c))
return false;
break;
case 'd':
if(strchr(pLeft,c)==NULL)
return false;
break;
}
}
return true;
}



eg.2

#include <memory>
#include <string>
#include <cstring>
#include <iostream>
using namespace std;

char oriLights[5];
char lights[5];
cahr result[5]
char switchs;

int GetBit(char c,int i){
//取c的第i位
return (c>>i)&1;
}

void SetBit(char & c,int i,int v){
//设置c的第i位为v
if(v)
c |= (1<<i);
else
c &= ~(1<<i);
}

void Flip(char & c,int i){
//将c的第i位取反
c ^= (1<<i);
}

for(int n=0;n<64;++n){
switchs = n;
for(int i=0;i < 5;++i){
result = switchs;
for(int j=0;j < 6;++j){
if(GetBit(swichs,j)){
if(j>o)
Flip(lights[i],j-1);
Flip(lights[i],j);
if(j<5)
Flip(lights[i],j+1);
}
}
if(i<4)
lights[i+1] ^= switchs;
switchs = lights[i];
}
if(lights[4] == 0){
OutputResult(result);
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法