SSL_1692&&P2730【魔板】

魔板

题目

魔板


解析

看到题目,发现是BFS
想起要用哈希做
???
思路:
首先发现只有8个格,考虑用每三位二进制进行状压
压完后BFS,用一个224的string数组储存路径
结果显而易见:MLE
经过修改,发现读入顺序错误,修改
考虑省空间,将string扔进队列,用bool类代替
AC了!
结束了吗?不,还没有

code(BFS):

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
int t,t1[4],c[8],l,ll,ans,k,s,b[9]={
    
    1,1<<3,1<<6,1<<9,1<<12,1<<15,1<<18,1<<21,1<<24};
bool f[1<<24];
queue <int> a;
queue <string> d;
string e;
void bfs()
{
    
    
	while(!a.empty())
	{
    
    
		t=a.front(),e=d.front(),a.pop(),d.pop();
		if(t==ans)
		{
    
    
			printf("%d\n",e.size());
			cout<<e;
			return;
		}
		l=t;
		for(int i=7;i>=0;i--)
		{
    
    
			ll=l;
			ll>>=3;
			ll<<=3;
			c[i]=7&(l-ll);
			l>>=3;
		}
		k=c[4]*b[7]+c[5]*b[6]+c[6]*b[5]+c[7]*b[4]+c[0]*b[3]+c[1]*b[2]+c[2]*b[1]+c[3];
		if(!f[k])f[k]=1,d.push(e+'A'),a.push(k);
		k=c[3]*b[7]+c[0]*b[6]+c[1]*b[5]+c[2]*b[4]+c[7]*b[3]+c[4]*b[2]+c[5]*b[1]+c[6];
		if(!f[k])f[k]=1,d.push(e+'B'),a.push(k);
		k=c[0]*b[7]+c[5]*b[6]+c[1]*b[5]+c[3]*b[4]+c[4]*b[3]+c[6]*b[2]+c[2]*b[1]+c[7];
		if(!f[k])f[k]=1,d.push(e+'C'),a.push(k);
	}
}
int main()
{
    
    
	for(int i=0;i<=3;i++)
	{
    
    
		scanf("%d",&t);
		ans<<=3;
		ans+=t-1;
	}
	for(int i=0;i<=3;i++)scanf("%d",&t1[i]);
	for(int i=3;i>=0;i--)
	{
    
    
		ans<<=3;
		ans+=t1[i]-1;
	}
	f[343980]=1,a.push(343980),d.push("");
	bfs();
	return 0;
}

我们非常欣喜地发现似乎与哈希并无关联
同时空间仍然不算好
哈希优化空间,然后达到完美平衡
完美AC
66ms/4.86MB

code(Hash):

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
int t,t1[4],c[8],l,ll,ans,k,s,b[9]={
    
    1,1<<3,1<<6,1<<9,1<<12,1<<15,1<<18,1<<21,1<<24};
bool f[1<<24];
queue <int> a;
queue <string> d;
string e;
void bfs()
{
    
    
	while(!a.empty())
	{
    
    
		t=a.front(),e=d.front(),a.pop(),d.pop();
		if(t==ans)
		{
    
    
			printf("%d\n",e.size());
			cout<<e;
			return;
		}
		l=t;
		for(int i=7;i>=0;i--)
		{
    
    
			ll=l;
			ll>>=3;
			ll<<=3;
			c[i]=7&(l-ll);
			l>>=3;
		}
		k=c[4]*b[7]+c[5]*b[6]+c[6]*b[5]+c[7]*b[4]+c[0]*b[3]+c[1]*b[2]+c[2]*b[1]+c[3];
		if(!f[k])f[k]=1,d.push(e+'A'),a.push(k);
		k=c[3]*b[7]+c[0]*b[6]+c[1]*b[5]+c[2]*b[4]+c[7]*b[3]+c[4]*b[2]+c[5]*b[1]+c[6];
		if(!f[k])f[k]=1,d.push(e+'B'),a.push(k);
		k=c[0]*b[7]+c[5]*b[6]+c[1]*b[5]+c[3]*b[4]+c[4]*b[3]+c[6]*b[2]+c[2]*b[1]+c[7];
		if(!f[k])f[k]=1,d.push(e+'C'),a.push(k);
	}
}
int main()
{
    
    
	for(int i=0;i<=3;i++)
	{
    
    
		scanf("%d",&t);
		ans<<=3;
		ans+=t-1;
	}
	for(int i=0;i<=3;i++)scanf("%d",&t1[i]);
	for(int i=3;i>=0;i--)
	{
    
    
		ans<<=3;
		ans+=t1[i]-1;
	}
	f[343980]=1,a.push(343980),d.push("");
	bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhanglili1597895/article/details/112970987