WA#12
查看原帖
WA#12
785964
zzhbpyy楼主2024/4/20 13:17
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct Jz{
	short a[4][4];int t;
	Jz(){
		t=0;
		memset(a,0,sizeof a);
	}
	Jz(string s){
		for(int i=1;i<=3;i++)
			for(int j=1;j<=3;j++)a[i][j]=s[i*3+j-4]-'0';
	}
}ed("123804765");
inline bool operator <(Jz a,Jz b){return a.a[0][1]<b.a[0][1];}
string s;int di[4][2]={{0,1},{1,0},{-1,0},{0,-1}},bs=10;
priority_queue<pair<int,Jz>,vector<pair<int,Jz>>,greater<pair<int,Jz>>>q;
inline int h(Jz x,Jz y){
	int ans=0;
	for(int i=1;i<=3;i++)
		for(int j=1;j<=3;j++)
			if(x.a[i][j]!=y.a[i][j])ans++;
	return ans;
}
inline int gh(Jz x){
	int res=0;
	for(int i=1;i<=3;i++)
		for(int j=1;j<=3;j++)
			res*=bs,res+=x.a[i][j];
	return res;
}
set<int>st;//9876543210
signed main(){
	cin>>s;Jz x(s);
	q.push({h(x,ed),x});
	st.insert(gh(x));
	while(!q.empty()){
		Jz s=q.top().second;q.pop();
		int ss,v,hh=h(s,ed);
		if(!hh){
			cout<<s.t;
			return 0;
		}
		for(int i=1;i<=3;i++)
			for(int j=1;j<=3;j++)
				if(!s.a[i][j]){ss=i,v=j;break;}
		for(int i=0;i<4;i++){
			int x=ss+di[i][0],y=v+di[i][1];
			if(x<1||x>3||y<1||y>3)continue;
			Jz d=s;
			swap(d.a[x][y],d.a[ss][v]);d.t=s.t+1;
			if(st.find(gh(d))!=st.end())continue;
			st.insert(gh(d));
			q.push({h(d,ed)+d.t,d});
		}
	}
	return 0;
}
2024/4/20 13:17
加载中...