很少去自己構建枚舉法,一般遇到題就是直接的DFS,BFS顯然這樣的編碼複雜度很高。太久沒有做題了連這道水題都用了我一上午,也對自己的思維有協助吧,簡單的事情複雜化了。實在不是我所希望的啊... 調試了N久都沒弄出來!
好吧說說這題的思路:
首先明確的一點就是這題不需要用到DFS,用DFS和BFS的話就要用位操作壓縮狀態,一位位操作還是很方便的,但是兩位位操作寫起來就不那麼好看了。我們知道,對於9個位置,在同一個位置按下4次的話,相當於沒有按下。於是對於同一個位置最多按下3次咯。枚舉的就是這九個位置,利用九重for就可以了= =。驗證原始的輸入數組通過我們的枚舉操作之後如果全都變為12的話,就輸出好了,前置字元為零也使得代碼難看!
Code貼了...:
#include<stdio.h>using namespace std;bool check( int *b,int *r ){ int temp[10]; for( int i=1;i<=9;i++ ) temp[i]=r[i]; for( int i=1;i<=b[1];i++ ){ temp[1]++;temp[2]++;temp[4]++;temp[5]++; } for( int i=1;i<=b[2];i++ ){ temp[1]++;temp[2]++;temp[3]++; } for( int i=1;i<=b[3];i++ ){ temp[2]++;temp[3]++;temp[5]++;temp[6]++; } for( int i=1;i<=b[4];i++ ){ temp[1]++;temp[4]++;temp[7]++; } for( int i=1;i<=b[5];i++ ){ temp[2]++;temp[4]++;temp[5]++;temp[6]++;temp[8]++; } for( int i=1;i<=b[6];i++ ){ temp[3]++;temp[6]++;temp[9]++; } for( int i=1;i<=b[7];i++ ){ temp[4]++;temp[5]++;temp[7]++;temp[8]++; } for( int i=1;i<=b[8];i++ ){ temp[7]++;temp[8]++;temp[9]++; } for( int i=1;i<=b[9];i++ ){ temp[5]++;temp[6]++;temp[8]++;temp[9]++; } for( int i=1;i<=9;i++ ) { temp[i]%=4; if( temp[i] ) return false; } return true;}int main(){ int b[10]; int r[10]; freopen( "clocks.in","r",stdin ); freopen( "clocks.out","w",stdout ); for( int i=1;i<=9;i++ ) { scanf( "%d",&r[i] ); r[i]%=12;r[i]/=3;}for( b[1]=0;b[1]<=3;b[1]++ )for( b[2]=0;b[2]<=3;b[2]++ )for( b[3]=0;b[3]<=3;b[3]++ )for( b[4]=0;b[4]<=3;b[4]++ )for( b[5]=0;b[5]<=3;b[5]++ )for( b[6]=0;b[6]<=3;b[6]++ )for( b[7]=0;b[7]<=3;b[7]++ )for( b[8]=0;b[8]<=3;b[8]++ )for( b[9]=0;b[9]<=3;b[9]++ ){ if( check(b,r) ) { bool flag=false; for( int i=1;i<=b[1];i++ ) if( flag==false ){printf("1");flag=true;}else printf(" 1"); for( int i=1;i<=b[2];i++ ) if( flag==false ){printf("2");flag=true;}else printf(" 2"); for( int i=1;i<=b[3];i++ ) if( flag==false ){printf("3");flag=true;}else printf(" 3"); for( int i=1;i<=b[4];i++ ) if( flag==false ){printf("4");flag=true;}else printf(" 4"); for( int i=1;i<=b[5];i++ ) if( flag==false ){printf("5");flag=true;}else printf(" 5"); for( int i=1;i<=b[6];i++ ) if( flag==false ){printf("6");flag=true;}else printf(" 6"); for( int i=1;i<=b[7];i++ ) if( flag==false ){printf("7");flag=true;}else printf(" 7"); for( int i=1;i<=b[8];i++ ) if( flag==false ){printf("8");flag=true;}else printf(" 8"); for( int i=1;i<=b[9];i++ ) if( flag==false ){printf("9");flag=true;}else printf(" 9"); printf( "\n" ); return 0; } } return 0;}