一维密码锁(可能没有解)
第一个按钮按或者不按
#include<iostream> #include<cstring> #include<algorithm> #include<bitset> using namespace std; int main() { string line; bitset<32> lock; int mintimes=99999999;//无穷大 cin>>line; bitset<32> sourcelock(line); cin>>line; bitset<32> targetlock(line); int n=line.size(); for(int p=0;p<2;++p) { lock=sourcelock; int times=0; int nextbutton=p; for(int i=0;i<n;++i) { if(nextbutton==1) { ++times; if(i>0) lock.flip(i-1); lock.flip(i); if(i<n-1) lock.flip(i+1); } if(lock[i]!=targetlock[i]) nextbutton=1; else nextbutton=0; if(lock==targetlock) { mintimes=min(mintimes,times); } } } if(mintimes==99999999) { cout<<"impossible\n"; } else { cout<<mintimes<<endl; } }
二维熄灯问题
枚举第一行所有情况
#include<iostream> #include<bitset> #include<cstring> #include<memory> using namespace std; bitset<6> source[5],lights[5],res[5],line; int main() { int T; cin>>T; for(int t=1;t<=T;++t) { for(int i=0;i<5;i++) { for(int j=0;j<6;j++) { int x; cin>>x; source[i].set(j,x); } } for(int n=0;n<64;++n) { for(int i=0;i<5;i++) lights[i]=source[i]; line=n; for(int i=0;i<5;++i) { res[i]=line; for(int j=0;j<6;++j) { if(line.test(j)) { if(j>0) lights[i].flip(j-1); lights[i].flip(j); if(j<5) lights[i].flip(j+1); } } if(i<4) lights[i+1]^=line; line=lights[i]; } if(lights[4].none()) { cout<<"PUZZLE #"<<t<<"\n"; for(int i=0;i<5;++i) { for(int j=0;j<6;++j) { cout<<res[i][j]<<" "; } cout<<endl; } } } } }
拨钟问题
九重循环枚举所有操作
#include<iostream> #include<string.h> using namespace std; int main() { int a[11]; int change[11]; int best[11]; int minCount = 999999; for(int i = 1;i<=9;++i) { cin >>a[i]; } memset(change,0,sizeof(change)); int sum = 0; for(change[1] = 0;change[1]<4;change[1]++) for(change[2] = 0;change[2]<4;change[2]++) for(change[3] = 0;change[3]<4;change[3]++) for(change[4] = 0;change[4]<4;change[4]++) for(change[5] = 0;change[5]<4;change[5]++) for(change[6] = 0;change[6]<4;change[6]++) for(change[7] = 0;change[7]<4;change[7]++) for(change[8] = 0;change[8]<4;change[8]++) for(change[9] = 0;change[9]<4;change[9]++) { sum = 0; sum+= (a[1]+change[1]+change[2]+change[4])%4;//A只有1 2 4操作能改变A ,%4拨4次相当于没有拨 sum+= (a[2]+change[1]+change[2]+change[3]+change[5])%4;//B sum+= (a[3]+change[2]+change[3]+change[6])%4;//C sum+= (a[4]+change[1]+change[4]+change[5]+change[7])%4;//D sum+= (a[5]+change[1]+change[3]+change[5]+change[7]+change[9])%4;//E sum+= (a[6]+change[3]+change[5]+change[6]+change[9])%4;//F sum+= (a[7]+change[4]+change[7]+change[8])%4;//G sum+= (a[8]+change[5]+change[7]+change[8]+change[9])%4;//H sum+= (a[9]+change[6]+change[8]+change[9])%4;//I if(sum == 0)//能恢复 { int count = 0; for(int j=1;j<=9;j++) { count += change[j]; } if(count < minCount) { minCount = count; memcpy(best,change,sizeof(change)); } for(int j=1;j<=9;j++) { while(best[j]--) { cout << j<<" "; } } } } return 0; }
标签:大法,int,flip,枚举,bitset,line,include,change From: https://www.cnblogs.com/weinan030416/p/17060569.html