[usaco3.2.5]msquare

  题目传送门:http://www.nocow.cn/index.php/Translate:USACO/msquare

  这道题bfs+hash,但想到要判重的数字不多,就直接用了map,数组传递有些麻烦,所以直接写在了一起,会有点乱

  

/*
ID:abc31261
LANG:C++
TASK:msquare
*/

#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<iostream>
using namespace std;
const int n=20;
int numend,a[n];
map<int,int> hash;
string anss="";

int sum(int num[n])
{
    int i,l=0;
    for (i=1;i<=8;i++)l+=num[i]*a[i];
    return l;
}

void init()
{
     int i,j,x=1,end[n];
     for (i=1;i<=8;i++)scanf("%d",&end[i]);
     swap(end[5],end[8]); swap(end[6],end[7]);
     for (i=8;i>=1;i--)
     {
         a[i]=x;
         x=x*10;
     }
     numend=sum(end);
}

void bfs()
{
    queue<int> q;
    queue<string> q1;
    hash.clear();
    q.push(12348765);  q1.push(""); hash[12348765]=1;
    while (!q.empty())
    {
        int i,j,j1,x=q.front(),num1[n],num2[n];
        string s=q1.front();
        q.pop(); q1.pop();
        if (s=="BCABCCB")
        {
           i=1;
        }
        if (x==numend)
        {
            anss=s;
            return;
        }
        for (i=1;i<=8;i++)
        {
            num1[i]=x/a[i];
            x=x%a[i];
        }    
        memcpy(num2,num1,sizeof(num1));               //第一种操作 
        for (i=1;i<=4;i++)swap(num2[i],num2[i+4]);
        j=sum(num2);
        if (hash[j]==0)
        {
            hash[j]=1;
            q.push(j);
            q1.push(s+"A");
        }
        
        memcpy(num2,num1,sizeof(num1));            //第二种操作 
        for (i=4;i>=2;i--)
        {
            swap(num2[i],num2[i-1]);
            swap(num2[i+4],num2[i+3]);
        }
        j=sum(num2);
        if (hash[j]==0)
        {
            hash[j]=1;
            q.push(j);
            q1.push(s+"B");
        }
        
        memcpy(num2,num1,sizeof(num1));           //第三种操作 
        swap(num2[2],num2[3]);
        swap(num2[6],num2[7]);
        swap(num2[2],num2[7]);
        j=sum(num2);
        if (hash[j]==0)
        {
            hash[j]=1;
            q.push(j);
            q1.push(s+"C");
        }
    }
}

int main()
{
    freopen("msquare.in","r",stdin);
    freopen("msquare.out","w",stdout);   
    init();
    bfs();        
    cout<<anss.length()<<endl<<anss<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Sun-Sea/p/5143775.html