Loj上过了luogu没过求助
查看原帖
Loj上过了luogu没过求助
264548
Tangent233楼主2023/11/6 12:48
#include<bits/stdc++.h>
using namespace std;
unsigned long long bas=10007;
char ans[10][10]={{0},{0,'1','1','1','1','1'},{0,'0','1','1','1','1'},{0,'0','0','*','1','1'},{0,'0','0','0','0','1'},{0,'0','0','0','0','0'}};
char now[10][10];
map<unsigned long long,int> vis;
unsigned long long gethash(char arr[10][10])
{
	unsigned long long hsh=0;
	for(int i=1;i<=5;i++)
		for(int j=1;j<=5;j++)
			hsh=hsh*bas+arr[i][j];
	return hsh;
}
int getval(char arr[10][10])
{
	int ans1=0;
	for(int i=1;i<=5;i++)
		for(int j=1;j<=5;j++)
			if(arr[i][j]!=ans[i][j])
				ans1++;
	return ans1;
}
struct node
{
	char arr[10][10];
	int step;
	int val;
	int operator <(const node b)const
	{
		return val>b.val;
	}
};
priority_queue<node> q;//queue<node> q;
int d[10][3]={{0},{0,1,2},{0,-1,2},{0,-1,-2},{0,1,-2},{0,2,1},{0,2,-1},{0,-2,1},{0,-2,-1}};
unsigned long long endhsh=0;
int main()
{
	endhsh=gethash(ans);
	int T;
	cin>>T;
	getchar();
	while(T--)
	{
		memset(now,0,sizeof(now));
		while(!q.empty())
			q.pop();
		vis.clear();
		//q.clear();
		for(int i=1;i<=5;i++)
		{
			for(int j=1;j<=5;j++)
				now[i][j]=getchar();
			getchar();
		}
		node tmp;
		tmp.step=0;
		for(int i=1;i<=5;i++)
			for(int j=1;j<=5;j++)
				tmp.arr[i][j]=now[i][j];
		tmp.val=tmp.step+getval(tmp.arr);
		q.push(tmp);
		int flag=0;
		while(!q.empty())
		{
			tmp=q.top();
			q.pop();
			int si,sj=0;
			if(vis[gethash(tmp.arr)])
				continue;
			if(tmp.val>16)
				continue;
			for(int i=1;i<=5;i++)
				for(int j=1;j<=5;j++)
				{
					if(tmp.arr[i][j]=='*')
					{
						si=i;
						sj=j;
					}
					now[i][j]=tmp.arr[i][j];
				}
			if(gethash(now)==endhsh)
			{
				cout<<tmp.step<<endl;
				flag=1;
				break;
			}
			vis[gethash(tmp.arr)]=1;
			for(int i=1;i<=8;i++)
			{
				int ni=si+d[i][1],nj=sj+d[i][2];
				if(ni>=1&&ni<=5&&nj>=1&&nj<=5)
				{
					node tmp2=tmp;
					swap(tmp2.arr[ni][nj],tmp2.arr[si][sj]);
					tmp2.step=tmp.step+1;
					tmp2.val=tmp2.step+getval(tmp2.arr);
					q.push(tmp2);
				}
			}
		}
		if(flag==0)
			cout<<-1<<endl;
	}
	return 0;
}

loj记录

2023/11/6 12:48
加载中...