poj1077 Eight —— 正向bfs+康拓

来源:互联网 发布:日本dvd播放软件 编辑:程序博客网 时间:2024/05/26 09:53

题目链接:http://poj.org/problem?id=1077


代码如下:

#include<iostream>//poj1077 正向bfs+康拓#include<cstring>#include<cstdio>#define MAX 400000#define AIM 46234using namespace std;int mov[4][2] = {-1,0,1,0,0,-1,0,1}, fac[9] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320};char dir[] = "udlr";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;}bool bfs(){    Node next;    int front = 0, rear = 1;    q[front] = cur;    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;                if(next.status==AIM) {cur = next; return true;}                q[rear++] = next;             }       }        front++;    }    return false;}void pri(){    char ch = cur.dir;    if(cur.fa>0) {cur = q[cur.fa];pri();}    putchar(ch);}int main(){    char ch[50];    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';        }        memset(vis,false,sizeof(vis));        vis[cantor(cur.s)] = true;        if(bfs())            pri(), putchar('\n');        else            cout<<"unsolvable"<<endl;    }    return 0;}


0 0
原创粉丝点击