BFS + 状态压缩 POJ 2965 The Pilots Brothers' refrigerator

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>

using namespace std;

char c;

int m;

int sp[999999];

struct Q
{
    int sta,ans,r,c,pre;
} q[999999],t,t1;

int top = 0,sum = 999999;

bool vis[65536];

void search(int site,int sta,int ans)
{
    int s = 0,e = 0;
    q[e].r = q[e].c = q[e].pre = -1;
    q[e].sta = sta;
    q[e++].ans = ans;

    vis[sta] = true;

    int i,j;

    while(s != e)
    {
        t1 = q[s++];
        if(t1.sta == 65535)
        {
            sum = t1.ans;
            m = s-1;
            return;
        }
        for(i = 1; i <= 4; i++)
            for(j = 1; j <= 4; j++)
            {
                t = t1;
                for(site = i*4-3; site <= i*4; site++)
                {
                    t.sta ^= (1<< (site-1));
                }
                site = j%4;
                if(site == 0)
                    site = 4;
                for(; site <= 16; site += 4)
                {
                    t.sta ^= (1<< (site-1));
                }

                t.sta ^= (1<< i*4+j-5);

                if(vis[t.sta] == false)
                {
                    t.ans++;
                    q[e] = t;
                    q[e].pre = s-1;

                    q[e].r = i;
                    q[e++].c = j;
                    vis[t.sta] = true;
                }
            }
    }
}

void output_path(int m)//递归输出路径
{
    if(q[m].pre == -1)
        return;
    output_path(q[m].pre);
    printf("%d %d\n",q[m].r,q[m].c);
}

int main()
{
    int i,j;

    char s[10];

    sum = 999999;

    memset(vis,false,sizeof(vis));

    int t;

    for(m = 0,t = 1,i = 0; i < 4; i++)
    {
        scanf("%s",s);
        for(j = 0; j < 4; j++)
        {
            if(s[j] == '-')
                m += t;
            t *= 2;
        }

    }

    search(1,m,0);

    cout<<sum<<endl;

    output_path(m);

    return 0;
}

 

你可能感兴趣的:(BFS + 状态压缩 POJ 2965 The Pilots Brothers' refrigerator)