夏夜、

心若平似镜、何题不AC。

usaco the clocks DFS

迭代加深搜索,预处理9个move.

//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<sstream>
#include<cmath>
#include<climits>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
#define pb(a) push(a)
#define INF 0x1f1f1f1f
#define lson idx<<1,l,mid
#define rson idx<<1|1,mid+1,r
#define PI  3.1415926535898
template<class T> T min(const T& a,const T& b,const T& c) {
    return min(min(a,b),min(a,c));
}
template<class T> T max(const T& a,const T& b,const T& c) {
    return max(max(a,b),max(a,c));
}
void debug() {
#ifdef ONLINE_JUDGE
#else

    freopen("d:\\in1.txt","r",stdin);
    freopen("d:\\out1.txt","w",stdout);
#endif
}
int getch() {
    int ch;
    while((ch=getchar())!=EOF) {
        if(ch!=' '&&ch!='\n')return ch;
    }
    return EOF;
}

int Clock[9];
int rota[10][9];
void init()
{
    char rule[10][10]={"","ABDE","ABC","BCEF",
    "ADG","BEDFH","CFI","DEGH","GHI","EFHI"};
    for(int i=1;i<=9;i++)
    {
        for(int j=0;rule[i][j]!='\0';j++)
        {
            int id=rule[i][j]-'A';
            rota[i][id]=1;
        }
    }
}



int res[30];
int vis[9];
int clo[9];
int check()
{
    for(int i=0;i<9;i++)
        if(clo[i]!=0)
            return 0;
    return 1;
}
int dfs(int k,int t,int step)
{
    if(t==step)
    {
        return check();
    }
    for(int i=k;i<=9;i++)if(vis[i]<3)
    {
        vis[i]++;
        for(int j=0;j<9;j++)
            clo[j] = (clo[j]+rota[i][j])%4;
        res[t]=i;
        if(dfs(i,t+1,step))return 1;
        vis[i]--;
        for(int j=0;j<9;j++)
            clo[j] = (clo[j]+4-rota[i][j])%4;

    }
    return 0;
}
int Search()
{
    for(int step=1;step<=27;step++)
    {
        memset(vis,0,sizeof(vis));
        memcpy(clo,Clock,sizeof(Clock));
        if(dfs(1,0,step))return step;
    }
    return -1;
}
int main()
{
    freopen("clocks.in","r",stdin);
    freopen("clocks.out","w",stdout);
    init();
    for(int i=0;i<9;i++)
    {
        scanf("%d",&Clock[i]);
        Clock[i]=Clock[i]/3%4;
    }
    int step=Search();
    for(int i=0;i<step;i++)
        printf("%d%c",res[i],i+1==step?'\n':' ');
    return 0;
}
View Code

 

posted on 2014-02-20 14:12  BMan、  阅读(174)  评论(0编辑  收藏  举报

导航