首页 > 代码库 > hdu 2209 bfs+状压

hdu 2209 bfs+状压

http://acm.hdu.edu.cn/showproblem.php?pid=2209


不知为啥有种直觉,会出状压+搜索的题,刷几道先

简单的BFS,状压表示牌的状态,

//#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <map>
#include <set>
#include <queue>
using namespace std;

#define ls(rt) rt*2
#define rs(rt) rt*2+1
#define ll long long
#define ull unsigned long long
#define rep(i,s,e) for(int i=s;i<e;i++)
#define repe(i,s,e) for(int i=s;i<=e;i++)
#define CL(a,b) memset(a,b,sizeof(a))
#define IN(s) freopen(s,"r",stdin)
#define OUT(s) freopen(s,"w",stdout)
const ll ll_INF = ((ull)(-1))>>1;
const double EPS = 1e-8;
const double pi = acos(-1.0);
const int INF = 100000000;

int len,s;
int vis[1<<21];
char in[50];
int legal[25];
struct Node{
    int s;
    int cnt;
    Node(int ss,int cc):s(ss),cnt(cc){}
};

void change()
{
    s=0;
    len=strlen(in);
    for(int i=0;i<len;i++)
    {
        s<<=1;
        if(in[i] == '1')s+=1;
    }
}

int bfs()
{
    queue<Node>q;
    q.push(Node(s,0));
    CL(vis,0);
    vis[s]=1;
    while(!q.empty())
    {
        Node tp=q.front();q.pop();///
        if(tp.s==0)return tp.cnt;
        int s,cnt=tp.cnt+1;
        for(int i=0;i<len;i++)
        {
            if(i==0)s=tp.s^3;
            else
            {
                if(i==len-1)s=tp.s^(3<<(len-2));//
                else s=(tp.s^(7<<(i-1)));
            }
            if(!vis[s])
            {
                vis[s]=1;
                q.push(Node(s,cnt));
            }

        }

    }
    return -1;
}

int main()
{
    //IN("hdu2209.txt");
    while(~scanf("%s",in))
    {
        change();
        int ans=bfs();
        if(ans==-1)puts("NO");
        else printf("%d\n",bfs());
    }
    return 0;
}

 

hdu 2209 bfs+状压