[BZOJ 1054][HAOI 2008]移動玩具(BFS+判重)

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   os   sp   for   on   

題目連結:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1054

真是水題,感謝HAOI送的福利範例23333

裸BFS,用string做判重,會八數位就會這題。

注意由於隊列中狀態數很多,一定要把隊列的數組開大點!!!

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <string>#include <algorithm>#include <map>#define MAXN 5using namespace std;map<string,bool>visit;int tmp[MAXN][MAXN],nowstatus[MAXN][MAXN];int xx[]={1,-1,0,0},yy[]={0,0,1,-1};bool inMap(int x,int y){    if(x<1||x>4||y<1||y>4) return false;    return true;}string GetPermutationFromArray(){    string ans="";    for(int i=1;i<=4;i++)        for(int j=1;j<=4;j++)            ans+=tmp[i][j]+'0';    return ans;}void GetArrayFromPermutaion(string s){    int p=0;    for(int i=1;i<=4;i++)        for(int j=1;j<=4;j++)            tmp[i][j]=s[p++]-'0';}struct node{    string status;    int step;}q[100000],first,goal;int h=0,t=0;int BFS(){    q[t++]=first;    visit[first.status]=true;    while(h<t)    {        node now=q[h++];        if(now.status==goal.status) return now.step;        GetArrayFromPermutaion(now.status);        for(int x=1;x<=4;x++)            for(int y=1;y<=4;y++)            {                if(tmp[x][y]==1) //(x,y)是玩具                {                    for(int dir=0;dir<4;dir++)                    {                        int tx=x+xx[dir],ty=y+yy[dir];                        if(!inMap(tx,ty)) continue;                        if(tmp[tx][ty]==0) //(tx,ty)是空地                        {                            node next;                            next.step=now.step+1;                            swap(tmp[x][y],tmp[tx][ty]);                            next.status=GetPermutationFromArray();                            if(!visit[next.status])                            {                                visit[next.status]=true;                                q[t++]=next;                            }                            swap(tmp[x][y],tmp[tx][ty]);                        }                    }                }            }    }    return -1;}int main(){    string s;    first.step=0;    for(int i=1;i<=4;i++)    {        cin>>s;        first.status+=s;    }    for(int i=1;i<=4;i++)    {        cin>>s;        goal.status+=s;    }    printf("%d\n",BFS());    return 0;}



[BZOJ 1054][HAOI 2008]移動玩具(BFS+判重)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.