跳到正文

闲话

7.9总结

Super_Diu约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月10日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

T1 P1379 八数码难题

绿题?认真的?

其他部分哈广搜差不多,但就是中间的运行(移动)不一样

中间我还想过转成二维数组来做,但是发现用字符串操作更方便。。。

我们可以发现,在字符串中,往右移就是+3,往左移就是-3,上下就更简单了,+1和-1。这就是方向数组。

还有一些特殊情况要特判,就比如2,5,8要向右移就不行,因为会越界。还有一个特殊情况,就是3,6不能向左移。

注意细节!!!

Code:

C++
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=113+10;
int sx;
string a;
int fx[]={0,3,-3,1,-1};
struct node{
	int x,step;
	string s;
};
queue<node>q;
map<string,bool>mp;
void bfs(int x){
	q.push({x,0,a});
	mp[a]=1;
	while(!q.empty()){
		node t=q.front();
		q.pop();
		if(t.s=="123804765"){
			cout<<t.step;
			return;
		}
		for(int i=1;i<=4;i++){
			int tx=t.x+fx[i];
			if((t.x==2||t.x==5||t.x==8)&&i==3)continue;
			if((t.x==3||t.x==6)&&i==4)continue;
			if(tx>=0&&tx<9){
				swap(t.s[t.x],t.s[tx]);
				if(mp[t.s]==0){
					q.push({tx,t.step+1,t.s});
					mp[t.s]=1;
				}
				swap(t.s[t.x],t.s[tx]);
			}
		}
	}
}
int main(){
	ios::sync_with_stdio(0);
	cin>>a;
	for(int i=0;i<9;i++){
		if(a[i]=='0'){
			sx=i;
			break;
		}
	}
	bfs(sx);
	return 0;
}

T2 P2730 [USACO3.2] 魔板 Magic Squares

和上一题差不多,就只是多了几个函数(难写)

这题有三个完全不一样的移动方式,要注意,任何一点小瑕疵都会使程序出错

注意细节!!!

Code:

C++
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=114+10;
string ed,st="12345678";
struct node{
	string s;
	int step;
	string path;
};
map<string,bool>mp;
string A(string s){
	swap(s[0],s[7]);
	swap(s[1],s[6]);
	swap(s[2],s[5]);
	swap(s[3],s[4]);
	return s;
}
string B(string s){
	swap(s[3],s[2]);
	swap(s[2],s[1]);
	swap(s[1],s[0]);
	swap(s[4],s[5]);
	swap(s[5],s[6]);
	swap(s[6],s[7]);
	return s;
}
string C(string s){
	swap(s[2],s[5]);
	swap(s[2],s[1]);
	swap(s[1],s[6]);
	return s;
}
int main(){
	ios::sync_with_stdio(0);
	for(int i=1;i<=8;i++){
		char c;
		cin>>c;
		ed+=c;
	}
	mp[st]=1;
	queue<node>q;
	q.push({st,0,""});
	while(!q.empty()){
		node t=q.front();
		q.pop();
		if(t.s==ed){
			cout<<t.step<<'\n'<<t.path<<'\n'; 
		}
		string ss=A(t.s);
		if(mp[ss]==0){
			mp[ss]=1;
			q.push({ss,t.step+1,t.path+'A'});
		}
		ss=B(t.s);
		if(mp[ss]==0){
			mp[ss]=1;
			q.push({ss,t.step+1,t.path+'B'});
		}
		ss=C(t.s);
		if(mp[ss]==0){
			mp[ss]=1;
			q.push({ss,t.step+1,t.path+'C'});
		}
	}
	return 0;
}

bye~

原文