hdu1043 Eight —— 反向bfs+康拓

来源:互联网 发布:c语言 匈牙利 编辑:程序博客网 时间:2024/05/28 16:30

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1043


代码如下:

#include<iostream>//hdu1043 反向bfs+康拓 (多组数据,打表)#include<cstring>#include<cstdio>#define MAX 400000using namespace std;int aim, mov[4][2] = {-1,0,1,0,0,-1,0,1}, fac[9] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320};char dir[] = "durl", path[MAX][50];bool vis[MAX];struct Node{    int s[9];    int loc;    int status;    int fa;    char dir;};Node cur,q[MAX];int cantor(int s[]){    int sum = 0;    for (int i = 0; i < 9; i++)    {        int num = 0;        for (int j = i + 1; j < 9; j++)            if (s[j] < s[i])                num++;        sum += num*fac[9 - i - 1];    }    return sum + 1;}void crepath(Node end){    int len = 0;    int fa = end.fa;    path[end.status][len++] = end.dir;    while(fa>0)    {        path[end.status][len++] = q[fa].dir;        fa = q[fa].fa;    }    path[end.status][len] = 0;}bool bfs(){    Node next;    int front = 0, rear = 1;    for(int i = 0;i<8;i++) q[0].s[i] = i+1;    q[0].s[8] = 0, q[0].loc = 8, q[0].status = cantor(q[0].s);    vis[q[0].status] = true;    while (front < rear)    {        cur = q[front];        int x = cur.loc / 3;        int y = cur.loc % 3;        for (int i = 0; i < 4; i++)        {            int xx = x + mov[i][0];            int yy = y + mov[i][1];            if (xx < 0 || xx>2 || yy < 0 || yy>2)continue;            next = cur;            next.loc = xx * 3 + yy;            next.s[cur.loc] = next.s[next.loc];            next.s[next.loc] = 0;            next.fa = front;            next.dir = dir[i];            next.status = cantor(next.s);            if (!vis[next.status])             {                vis[next.status] = true;                crepath(next);                q[rear++] = next;             }       }        front++;    }    return false;}int main(){    char ch[50];    bfs();    while(gets(ch))    {        for(int i = 0,m = 0; ch[i]!=0; i++)        {            if(ch[i]==' ') continue;            if(ch[i]=='x') { cur.loc = m; cur.s[m++] = 0;}            else cur.s[m++] = ch[i]-'0';        }        aim = cantor(cur.s);        if(vis[aim])            puts(path[aim]);        else            cout<<"unsolvable"<<endl;    }    return 0;}


0 0
原创粉丝点击