usaco 1.4.2



BFS

/*
    ID: hongxdo1
    PROG: clocks
    LANG: C++
*/


#include 
<iostream>
#include 
<fstream>
#include 
<string>

using namespace std;

int const with[10][5= {{}{1,2,4,5},{1,2,3},{2,3,5,6},{1,4,7},{2,4,5,6,8},{3,6,9},{4,5,7,8},{7,8,9},{5,6,8,9}};
char t[270000][10], way[270000= {1}, use[270000][10];
unsigned 
int pre[270000];
string ans;

void bfs();
bool check(int);
void work(int , int , int );

int main()
{
    freopen(
"clocks.in","r",stdin);
    freopen(
"clocks.out""w", stdout);
    
for ( int i = 1, temp; i <= 9; i++)
    
{
        cin
>>temp;
        t[
0][i] = temp%12;
    }

    bfs();
    cout
<<ans<<endl;
    
return 0;
}


void bfs()
{
    
int tail = 0, head = -1;
    
while ( tail > head)
    
{
        head
++;
        
for (int i=way[head];i<=9;i++//i指示1~9种变化的一种
        {
            
if (use[head][i] < 3// 如果第i种变化少于4次. 每种变化最多3次
            {
                work(i, head, 
++tail);
                way[tail] 
= i;
                pre[tail] 
= head;  // t当中tail位置变化的前一种变化为 t当中head位置的变化.
                for ( int j = 1; j <= 9; j++)
                
{
                    use[tail][j] 
= use[head][j];
                }

                use[tail][i]
++;
                
if (check(tail))
                
{
                    ans 
= char(way[tail] + '0');
                    
for ( int j = pre[tail]; j!= 0; j = pre[j])
                    
{
                        ans 
= ' ' + ans;
                        ans 
= char(way[j] + '0'+ ans;
                    }

                    
return;
                }

            }

        }

    }

}


bool check(int k)
{
    
for ( int i = 1; i <=9; i++)
    
{
        
if (t[k][i]!= 0return false;
    }

    
return true;
}


void work(int k, int from, int cur)
{
    
for ( int i = 1; i <= 9; i++)
    
{
        t[cur][i] 
= t[from][i];
    }

    
for ( int i = 0; i <= 4 && with[k][i] != 0; i++)
    
{
        t[cur][with[k][i]] 
= (t[from][with[k][i]] + 3%12;
    }

}

posted @ 2009-07-24 03:03  SunnyHong  阅读(150)  评论(0)    收藏  举报