HDU 5012 Dice (BFS)


事实上是非常水的一道bfs,用字符串表示每一个状态,map判重就ok了。

题目链接:http://acm.hdu.edu.cn/showproblem.php?

pid=5012

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include<algorithm>
#include<string>
#include<queue>
#include<map>
#define N 7
using namespace std;

string a,b;
map<string,int> Hash;
struct node
{
    int t;
    string v;
};
int rot[4][7]={     //Rotation operation
    {0,4,3,1,2,5,6},    //left
    {0,3,4,2,1,5,6},    //right
    {0,6,5,3,4,1,2},    //front
    {0,5,6,3,4,2,1},    //back
};
int bfs()
{
    queue<node> q;
    node u,v;
    u.t=0; u.v=b;
    q.push(u);
    Hash[b]=1;
    while(!q.empty())
    {
        u=q.front();
        q.pop();
        if(u.v==a)
            return u.t;
        for(int i=0;i<4;i++)
        {
            v.v="";
            for(int j=1;j<7;j++)
                v.v+=u.v[rot[i][j]-1]; //~~
            if(!Hash[v.v])
            {
                v.t=u.t+1;
                q.push(v);
                Hash[v.v]=1;
            }
        }
    }
    return -1;
}
int main()
{
    string t;
    while(cin>>t)
    {
        a=b="";
        a+=t;
        for(int i=2;i<=6;i++)
        {
            cin>>t;
            a+=t;
        }
        for(int j=1;j<=6;j++)
        {
            cin>>t;
            b+=t;
        }
        Hash.clear();
        cout<<bfs()<<endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/mengfanrong/p/5084705.html