hdu 1043 Eight

BFS+hash判重。

 

CODE:(TLE)

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include < set>
using  namespace std;

typedef  int State[ 9];
const  int MAXN =  1000003;
const  int dx[] = {- 1, 1, 0, 0};
const  int dy[] = { 0, 0,- 1, 1};
char dir[ 5] =  " udlr ";
int goal[ 9] = { 123456780}; 
State st[MAXN];
int fa[MAXN], path[MAXN];
int first[MAXN], next[MAXN];
State state;


void init()
{
    memset(first, - 1sizeof(first));
    memset(fa,  0sizeof(fa));
    memset(path,  0sizeof(path));
}

int hash(State &s)
{
     int v =  0;
     for( int i =  0; i <  9; i++) v = v* 10 + s[i];
     return v%MAXN;
}

int try_to_insert( int s)
{
     int h = hash(st[s]);
     for( int v = first[h]; v!=- 1; v = next[v])
    {
         if(memcmp(st[v], st[s],  sizeof(st[s])) ==  0return  0;
    }
    next[s] = first[h];
    first[h] = s;
     return  1;
}

int check( int r,  int c)
{
     if(r >=  0 && r <  3 && c >=  0 && c <  3)     return  1;
      return  0;
}

int bfs()
{
    init();
     int front =  0, rear =  1;
    fa[ 0] = path[ 0] = - 1;
    try_to_insert( 0);
     while(front < rear)
    {
        State& s = st[front];
         if(memcmp(goal, s,  sizeof(s)) ==  0return front;
         int z;
         for(z =  0; z <  9; z++)  if(!s[z])  break;
         int x = z/ 3, y = z% 3;
         for( int i =  0; i <  4; i++)
        {
             int newx = x + dx[i];
             int newy = y + dy[i];
             int newz =  3*newx + newy;
             if(check(newx, newy))
            {
                State& t = st[rear];
                memcpy(&t, &s,  sizeof(s));
                t[newz] = s[z];
                t[z] = s[newz];
                 if(try_to_insert(rear))
                {
                    fa[rear] = front;
                    path[rear] = i;
                    rear++;
                }
            }
        }
        front++;
    }
     return - 1;
}

void print_path( int cur)
{
     if(cur)
    {
        print_path(fa[cur]);
        printf( " %c ", dir[path[cur]]);
    }
}

int main()
{
     char save[ 10];
     while(scanf( " %s ", save))
    {
         if(save[ 0] ==  ' x ')
        {
            st[ 0][ 0] =  0;
        }
         else st[ 0][ 0] = save[ 0]- ' 0 ';
         for( int i =  1; i <  9; i++)
        {
            scanf( " %s ", save);
             if(save[ 0] ==  ' x ')
            {
                st[ 0][i] =  0;
            }
             else st[ 0][i] = save[ 0]- ' 0 ';
        }
         int ans = bfs();
         if(ans != - 1)
        {
            print_path(ans);
            printf( " \n ");
        }
         else printf( " unsolvable\n ");
    }
     return  0;
}

 

你可能感兴趣的:(HDU)