hdu 5012 dfs+剪枝

来源:互联网 发布:linux的解压缩命令 编辑:程序博客网 时间:2024/06/05 19:23

两个剪枝:

1.因为转动过程会出现循环,所以要限制深度

2.因为重复状态没有意义,所以可以记录状态,防止重复搜索

然后模拟+搜索轻松过了

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace std;int a[7] , b[7];void rotate1 ( ){    int t1 = a[4] , t2 = a[3] , t3 = a[1] , t4 =a[2];    a[1] = t1 , a[2] = t2 , a[3] = t3 , a[4] = t4;}void rotate2 ( ){    int t1 = a[3] , t2 = a[4] , t3 = a[2] , t4 = a[1];    a[1] = t1 , a[2] =t2 , a[3] = t3 , a[4] = t4;}void rotate3 ( ){    int t1 = a[6] , t2 = a[5] , t5 = a[1] , t6 = a[2];    a[1] = t1 , a[2] = t2 , a[5]= t5 , a[6] = t6;}void rotate4 ( ){    int t1 = a[5] , t2 = a[6] , t5 = a[2] , t6 = a[1];    a[1] = t1 , a[2] = t2 , a[5] = t5 , a[6] = t6;}int  ans = 50;int used[5];bool vis[5][5][5][5];bool check ( ){    for ( int i = 1 ; i <= 6 ; i++ )        if ( a[i] != b[i] ) return false;    return true;}void back ( int c[] ){    for ( int i = 1 ; i <= 6 ; i++ )        a[i] = c[i];}void dfs ( int n = 0  ){    if ( check ( ) )     {        ans = min ( ans , n );        return;    }    if ( vis[used[1]][used[2]][used[3]][used[4]] ) return;    else vis[used[1]][used[2]][used[3]][used[4]] = 1;    int c[7];     for ( int i = 1 ; i <= 6 ; i++ ) c[i] = a[i];    if ( used[1] < 3 )    {        used[1]++;        rotate1 ( );        dfs ( n+1);        back ( c );        used[1]--;    }    if ( used[2] < 3  )    {        used[2]++;        rotate2 ( );        dfs ( n+1 );        back ( c );        used[2]--;    }    if ( used[3] < 3 )    {        used[3]++;        rotate3 ( );        dfs ( n+1 );        back ( c );        used[3]--;    }    if ( used[4] < 3  )    {        used[4]++;        rotate4 ( );        dfs ( n+1 );        back ( c );        used[4]--;    }}int main ( ){    while ( ~scanf ( "%d" , &a[1] ) )    {        ans = 50;        memset ( used ,  0 , sizeof ( used ) );        memset ( vis , 0 , sizeof ( vis ) );        for ( int i = 2 ; i <= 6 ; i++ ) scanf ( "%d" , &a[i] );        for ( int i = 1 ; i <= 6 ; i++ ) scanf ( "%d" , &b[i] );        dfs ( );        if ( ans == 50 ) puts ( "-1" );        else printf ( "%d\n" , ans );    }}


0 0