POJ 2965 The Pilots Brothers' refrigerator 状态压缩+枚举 , bfs

http://poj.org/problem?id=2965

跟 poj1753 一个类型的

题意:还是四行四列的格子 里面有+和- ,变换一个符号的同时,它所在的行和列也要变,求最少的步数

问题是记录路径 无语

开始用的queueu队列,记录路径 TLE  后来改成数组 记录前一个点 运行时间还是长。。。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<queue>
#define MAX 660000
using namespace std;
char a[18];
bool vis[1<<17]={0};
int add[16]={ 0x111f, 0x222f, 0x444f, 0x888f,
              0x11f1, 0x22f2, 0x44f4, 0x88f8,
              0x1f11, 0x2f22, 0x4f44, 0x8f88,
              0xf111, 0xf222, 0xf444, 0xf888
            };
struct Node
{
    int num,grid,pre,step;
}qu[MAX];

void bfs(int x)
{
    if(x==0)
    {
       cout<<'0'<<endl;
       return ;
    }
    int SUM=0,beg=0,end=0;
    qu[0].step=0;
    qu[0].num=x;
    vis[x]=1;
    while(beg<=end)
    {
        Node t=qu[beg];
        beg++;
        if(t.num==0)
        {
            cout<<t.step<<endl;
            while(1)
            {
                int a=t.grid;
                cout<<a/4+1<<" "<<a%4+1<<endl;
                t=qu[t.pre];
                if(t.step==0)
                break;
            }

        }
        for(int i=0;i<16;i++)
        {
            int inf=t.num^add[i];
            if(!vis[inf])
            {
               vis[inf]=1;
               end++;
               qu[end].num=inf;
               qu[end].step=t.step+1;
               qu[end].pre=beg-1;
               qu[end].grid=i;
            }
        }

    }


}

int main()
{
    int i,Sum=0;
    for(i=0;i<16;i++)
    {
        cin>>a[i];
        if(a[i]=='+')
           Sum+=1<<i;
    }
        bfs(Sum);


   return 0;
}

  

posted @ 2012-02-09 02:12  快乐.  阅读(181)  评论(0编辑  收藏  举报