POJ 1753 Flip Game 组合数递归算法
#include <iostream>
#include <math.h>
#include <stdlib.h>
#define PI 3.1415926
using namespace std;
int a[16]={0};
int result[16];
int b[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
bool check(int *a1){
for(int i=1;i<=15;i++){
if(a1[i]!=a1[i-1])return false;
}
return true;
}
void zuhe(int totalNum,int selectNum,int *result,int start,int resultStart,int resultNum){
if(selectNum==0){
int a2[16];
for (int j = 0; j < 16; ++j) {
a2[j]=a[j];
}
for (int i = 0; i < resultNum; ++i) {
if (a2[result[i]]==0)a2[result[i]]=1;
else a2[result[i]]=0;
int x=result[i]/4;
int y=result[i]%4;
if (y<=2){
if (a2[result[i]+1]==0)a2[result[i]+1]=1;
else a2[result[i]+1]=0;
}
if(y>=1){
if (a2[result[i]-1]==0)a2[result[i]-1]=1;
else a2[result[i]-1]=0;
}
if(x<=2){
if (a2[result[i]+4]==0)a2[result[i]+4]=1;
else a2[result[i]+4]=0;
}
if(x>=1){
if (a2[result[i]-4]==0)a2[result[i]-4]=1;
else a2[result[i]-4]=0;
}
}
if (check(a2)==true){
cout<<resultNum<<endl;
exit(0);
}
else return;
}
for(int i=start;i<=totalNum-selectNum;i++){
result[resultStart]=b[i];
zuhe(totalNum,selectNum-1,result,i+1,resultStart+1,resultNum);
}
}
int main(){
for(int i=0;i<16;i++){
char input;
cin>>input;
if (input=='b')a[i]=0;
else a[i]=1;
}
if(check(a)==true){
cout<<0<<endl;
return 0;
}
int changeNum=1;
for(changeNum=1;changeNum<=16;changeNum++){
zuhe(16,changeNum,result,0,0,changeNum);
}
cout<<"Impossible"<<endl;
}