hdu 1067 广搜+map

来源:互联网 发布:淘宝嘉年华报名入口 编辑:程序博客网 时间:2024/05/01 13:26

广搜+map

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1067

原帖地址:http://hi.baidu.com/ehoifivrahbkqur/item/b88b17c90d3c4e2e46d5c0f9

#include <iostream>#include <string>#include <map>#include<stdio.h>#include<string.h>#include<queue>using namespace std;map<string,int>m;struct re{    int ll[4][8];    int step;};void tostring(struct re a,char *str){    int i,j,k;    for(i=k=0;i<4;i++)        for(j=1;j<8;j++){            str[k++]=a.ll[i][j]/10+'a';            str[k++]=a.ll[i][j]%10+'a';        }    str[k]='\0';}int change(struct re *a,int pox,int poy){    int i,j;    struct re tem=*a;    if(poy==0||tem.ll[pox][poy-1]%10==7||tem.ll[pox][poy-1]==0)        return 0;    for(i=0;i<4;i++)        for(j=0;j<8;j++){            if(tem.ll[i][j]==tem.ll[pox][poy-1]+1){                a->ll[pox][poy]=a->ll[i][j];                a->ll[i][j]=0;                return 1;            }        }}int ju(struct re a){    int i,j;    for(i=10;i<50;i+=10)        for(j=1;j<8;j++)            if(a.ll[i/10-1][j-1]!=i+j)                return 0;    return 1;}int judge(struct re a){    char str[100];    tostring(a,str);    if(m[str]>0) return 1;    m[str]=1;    return 0;}int bfs(struct re a){    int i,j,step;    struct re tem,tem2;    queue<struct re>q;    a.step=0;    q.push(a);    m.clear();    while(!q.empty()){        tem=q.front();        q.pop();        step=tem.step;        for(i=0;i<4;i++)            for(j=0;j<8;j++){                if(tem.ll[i][j]==0){                    tem2=tem;                    if(change(&tem2,i,j)==0)                        continue;                    if(ju(tem2)) return step+1;                    if(judge(tem2)) continue;                    tem2.step=step+1;                    q.push(tem2);                }            }    }    return -1;}int main(void){    int T,i,j;    struct re a;    string ss;    map<string,int>m;    scanf("%d",&T);    while(T--){        for(i=0;i<4;i++)            for(j=1;j<8;j++){                scanf("%d",&a.ll[i][j]);                if(a.ll[i][j]%10==1)                    a.ll[i][j]=0;            }        a.ll[0][0]=11;        a.ll[1][0]=21;        a.ll[2][0]=31;        a.ll[3][0]=41;        if(ju(a)){            printf("0\n");            continue;        }        printf("%d\n",bfs(a));    }}


原创粉丝点击