USACO Section 1.4 The Clocks

来源:互联网 发布:如何隐藏mac桌面图标 编辑:程序博客网 时间:2024/04/29 16:27
/*ID: lucien23PROG: clocksLANG: C++*//* *广度优先遍历搜索 *需要适当剪枝 *结果存在内存分配问题 *最后采用枚举法通过测试 **/#include<iostream>#include<fstream>#include<string>#include<vector>using namespace std;typedef struct Solution{string strNums;int clocks[3][3];}Solution;int main(){ifstream infile("clocks.in");ofstream outfile("clocks.out");if(!infile || !outfile){cout<<"file operation failure!"<<endl;return -1;}string moves[9];moves[0]="ABDE";moves[1]="ABC";moves[2]="BCEF";moves[3]="ADG";moves[4]="BDEFH";moves[5]="CFI";moves[6]="DEGH";moves[7]="GHI";moves[8]="EFHI";Solution initSolut;for (int i=0;i<3;i++){for (int j=0;j<3;j++){infile>>initSolut.clocks[i][j];}}initSolut.strNums="";vector<string> solutions;//存储正确的解决方案int movesCnt[9];/* *每种移动方法最多执行3次,第4次又变回原来的位置 *且执行的先后顺序也不影响结果 **/for (movesCnt[0]=0;movesCnt[0]<4;movesCnt[0]++){for (movesCnt[1]=0;movesCnt[1]<4;movesCnt[1]++){for (movesCnt[2]=0;movesCnt[2]<4;movesCnt[2]++){for (movesCnt[3]=0;movesCnt[3]<4;movesCnt[3]++){for (movesCnt[4]=0;movesCnt[4]<4;movesCnt[4]++){for (movesCnt[5]=0;movesCnt[5]<4;movesCnt[5]++){for (movesCnt[6]=0;movesCnt[6]<4;movesCnt[6]++){for (movesCnt[7]=0;movesCnt[7]<4;movesCnt[7]++){for (movesCnt[8]=0;movesCnt[8]<4;movesCnt[8]++){Solution newSolut;newSolut.strNums="";for (int r=0;r<3;r++){for (int s=0;s<3;s++){newSolut.clocks[r][s]=initSolut.clocks[r][s];}}//旋转钟盘for (int i=0;i<9;i++){int len=moves[i].length();for (int j=0;j<movesCnt[i];j++){newSolut.strNums+=i+1+'0';for (int k=0;k<len;k++){int m=(moves[i][k]-'A')/3;int n=(moves[i][k]-'A')%3;newSolut.clocks[m][n]=(newSolut.clocks[m][n]+3)%12;if(newSolut.clocks[m][n]==0)newSolut.clocks[m][n]=12;}}}bool isSolut=true;for (int r=0;r<3;r++){for (int s=0;s<3;s++){if(isSolut && newSolut.clocks[r][s]!=12)isSolut=false;}}if(isSolut){solutions.push_back(newSolut.strNums);}}}}}}}}}}string strLowest=solutions[0];int len=solutions.size();for (int i=1;i<len;i++){if(solutions[i].length()<=strLowest.length() && solutions[i]<strLowest)strLowest=solutions[i];}len=strLowest.length();outfile<<strLowest[0];for (int i=1;i<len;i++){outfile<<" "<<strLowest[i];}outfile<<endl;return 0;}