后四个点TLE求助
查看原帖
后四个点TLE求助
592895
y_kx_b楼主2022/1/26 17:16
#include<queue>
#include<cstdio>
#include<string>
#include<cstdlib>
#define gc getchar
#include<algorithm>
#include<unordered_map>
using namespace std;
string read()
{
	string ret;
	int o=8;
	char ch=gc();
	while(o--)
	{
		while(ch<'1'||ch>'8')
			ch=gc();
		if(ch>'0'&&ch<'9')
			ret+=ch,ch=gc();
	}
	return ret;
}
string tar;
const string init="12345678";
inline string A(string x)
{
	string ret;
//	ret+=x[7]+x[6]+x[5]+x[4]+x[3]+x[2]+x[1]+x[0];
	for(int i=7;i>=0;i--)
		ret+=x[i];
	return ret;
}
const int B_T[8]={3,0,1,2,5,6,7,4};
inline string B(string x)
{
	string ret;
	for(int i=0;i<8;i++)
		ret+=x[B_T[i]];
	return ret;
}
const int C_T[8]={0,6,1,3,4,2,5,7};
inline string C(string x)
{
	string ret;
	for(int i=0;i<8;i++)
		ret+=x[C_T[i]];
	return ret;
}
struct node
{
	string x;
	int step;
	node(){}
	node(string a,int b):x(a),step(b){}
};
queue<node> q;
unordered_map<string,string> m1;
unordered_map<string,char> m2;
unordered_map<string,bool> m3;
char ans[10000],anscnt=0;
void bfs()
{
	while(!q.empty())
	{
		node top=q.front();
		if(top.x==tar)
		{
			printf("%d\n",top.step);
			for(int i=1;top.x!=init;i++)
			{
				ans[anscnt++]=m2[top.x];
				top.x=m1[top.x];
			}
			return;
		}
		q.pop();
		{
			string y=A(top.x);
			q.push(node(y,top.step+1));
			if(!m3[y])
				m1[y]=top.x,m2[y]='A',m3[y]=1;
		}
		{
			string y=B(top.x);
			q.push(node(y,top.step+1));
			if(!m3[y])
				m1[y]=top.x,m2[y]='B',m3[y]=1;
		}
		{
			string y=C(top.x);
			q.push(node(y,top.step+1));
			if(!m3[y])
				m1[y]=top.x,m2[y]='C',m3[y]=1;
		}
//		printf("%s\n",top.x.c_str());
	}
}
int main(){
//	string tar="12345678";
//	printf("%s\n%s\n%s",A(tar).c_str(),B(tar).c_str(),C(tar).c_str());
	tar=read();
	q.push(node(init,0));
	bfs();
	for(int i=0;anscnt--;i++)
	{
		printf("%c",ans[anscnt]);
		if(i==60)
			printf("\n"),i=0;
	}
	return 0;
}
2022/1/26 17:16
加载中...