hdoj 1430魔板

此題主要考察的是BFS預處理+hash,hash用了康託展開,其中比較糾結的是按字典序進行排序,我一直沒弄懂這個地方怎麼做,後來看了傻仔大神的解題報告http://www.cppblog.com/notonlysuccess/archive/2009/02/27/75087.aspx


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

struct node
{
    int m[8];
    int val;
};

struct fath
{
    int father;
    int way;
};

node map[40330];
fath root[40330];
int fac[8]={1,1,2,6,24,120,720,5040};

//康拓展開
int change_to_int(int s[])
{
    int t=0;
    int count;
    for(int i=0;i<8;i++)
    {
        count=0;
        for(int j=i+1;j<8;j++)
        {
            if(s[i]>s[j])
                count++;
        }
        t+=count*fac[8-i-1];
    }
    return t+1;
}

//變換
node change(node p,int s)
{
    node a;
    switch (s)
    {
        case 0:
            for(int i=0;i<8;i++)
            {
                a.m[i]=p.m[7-i];
            }
            a.val=change_to_int(a.m);
            break;
        case 1:
            a.m[0]=p.m[3];
            for(int i=1;i<4;i++)
            {
                a.m[i]=p.m[i-1];
            }
            a.m[7]=p.m[4];
            for(int i=5;i<8;i++)
            {
                a.m[i-1]=p.m[i];
            }
            a.val=change_to_int(a.m);
            break;
        case 2:
            int x;
            x=p.m[6];
            p.m[6]=p.m[5];
            p.m[5]=p.m[2];
            p.m[2]=p.m[1];
            p.m[1]=x;
            p.val=change_to_int(p.m);
            a=p;
            break;
    }
    return a;
}

//預處理
void BFS()
{
    node p,t;
    queue<node> v;
    memset(map,0,sizeof(map));
    memset(root,0,sizeof(root));
    for(int i=0;i<8;i++)
    {
        p.m[i]=i;
    }
    p.val=change_to_int(p.m);
    map[p.val]=p;
    root[p.val].father=-1;//這是初始點12345678
    v.push(p);
    while(!v.empty())
    {
        t=v.front();
        v.pop();
        for(int i=0;i<3;i++)
        {
            p=change(t,i);
            if(map[p.val].val==0)
            {
                map[p.val]=p;
                root[p.val].father=t.val;
                root[p.val].way='A'+i;
                v.push(p);
            }
        }
    }
}

int main()
{
    char s1[9];
    char s2[9];
    char s[100];
    int st[9],en[9];
    int pos[9];
    int end[8];
    char ws[1000];
    BFS();
    while(scanf("%s%s",s1,s2)!=EOF)
    {
        for(int i=0;i<8;i++)
        {
            st[i]=s1[i]-'1';
            en[i]=s2[i]-'1';
        }
        for(int i=0;i<8;i++)
        {
            pos[st[i]]=i;
        }
        for(int i=0;i<8;i++)
        {
            end[i]=pos[en[i]];
        }
        int key=change_to_int(end);
        int i=0;
        while(root[key].father!=-1)
        {
            ws[i]=root[key].way;
            key=root[key].father;
            i++;
        }
        ws[i]=0;
        strrev(ws);
        puts(ws);
    }
    return 0;
}

 


 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章