WA25pts,悬赏一关
查看原帖
WA25pts,悬赏一关
550933
Tjaweiof楼主2024/7/2 15:18

RT

#include<bits/stdc++.h>
using namespace std;
#define FILE(x) freopen(x".in", "r", stdin);freopen(x".out", "w", stdout);
string s;
map <string, int> g;
map <string, bool> vis;
priority_queue <pair <int, string>, vector <pair <int, string> >, greater <pair <int, string> > > q;
int h(string s){
	int res = 0;
	if (s[1] != '1' && s[1] != '0'){
		res++;
	}
	if (s[2] != '2' && s[2] != '0'){
		res++;
	}
	if (s[3] != '3' && s[3] != '0'){
		res++;
	}
	if (s[4] != '8' && s[4] != '0'){
		res++;
	}
	if (s[6] != '4' && s[6] != '0'){
		res++;
	}
	if (s[7] != '7' && s[7] != '0'){
		res++;
	}
	if (s[8] != '6' && s[8] != '0'){
		res++;
	}
	if (s[9] != '5' && s[9] != '0'){
		res++;
	}
	return res;
}
int zero_s_loc(string s){
	for (int i = 1; i <= 9; i++){
		if (s[i] == '0'){
			return i;
		}
	}
	return 114514;
}
void Astar(){
	g[s] = 0;
	vis[s] = true;
	q.push({h(s), s});
	while (!vis[" 123804765"]){
		auto u = q.top();
		q.pop();
		string t;
		int z = zero_s_loc(u.second);
		if (1 <= z - 3 && z - 3 <= 9){
			t = u.second;
			swap(t[z - 3], t[z]);
			if (!vis[t]){
				vis[t] = true;
				g[t] = g[u.second] + 1;
				q.push({g[t] + h(t), t});
			}
		}
		if (1 <= z - 1 && z - 1 <= 9){
			t = u.second;
			swap(t[z - 1], t[z]);
			if (!vis[t]){
				vis[t] = true;
				g[t] = g[u.second] + 1;
				q.push({g[t] + h(t), t});
			}
		}
		if (1 <= z + 1 && z + 1 <= 9){
			t = u.second;
			swap(t[z + 1], t[z]);
			if (!vis[t]){
				vis[t] = true;
				g[t] = g[u.second] + 1;
				q.push({g[t] + h(t), t});
			}
		}
		if (1 <= z + 3 && z + 3 <= 9){
			t = u.second;
			swap(t[z + 3], t[z]);
			if (!vis[t]){
				vis[t] = true;
				g[t] = g[u.second] + 1;
				q.push({g[t] + h(t), t});
			}
		}
	}
	return;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin >> s;
	s = " " + s;
	Astar();
	cout << g[" 123804765"];
	return 0;
}

2024/7/2 15:18
加载中...