题目地址 https://www.luogu.org/problemnew/show/P2133
1、考虑字符串变换规律,是交换相邻的两个数字
2、因为数字搜索没有明显的边界,所以可以考虑广度优先搜索,或者 迭代加深搜索;
以下是逐步分析
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 666667;
const int INF = 20021020;
bool vis [maxn],fl=false;
int ANS=0,f[maxn];
int dv[7]= {1000000,100000,10000,1000,100,10,1};
int qread() {
int x=0,f=1;
char ch=getchar();
while (ch>'9'||ch<'0') {
if(ch=='-')f=-1;
ch=getchar();
}
while (ch>='0'&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
}
return f*x;
}
int st,ed;
dv数组方便于把一个六位整数拆分开,它的具体操作可以参见下面的代码。
maxn,INF分别代表最大组合情况和绝大值。
数组vis用作判重,f数组可以执行剪枝。
全局变量 ANS用作枚举答案。
仍有部分数组空间浪费了,例如vis[659000]等
int qread()是快速读入函数,习惯性的加上
st代表起始位置,ed代表结束位置
以上是并不完美的开头
int take_out(int x,int w) {
return (x/dv[w])%10;
}
int cha(int x,int w) {
int t1=take_out(x,w);
int t2=take_out(x,w+1);
return t2*dv[w]+t1*dv[w+1]+ x/dv[w-1]*dv[w-1]+x%(dv[w+1]);
}
x/dv[w]可以砍掉x第w位以后的数,然后对10取余可以得到特定位。
函数int cha(int x,int w)交换两位数字。它基于take_out函数。
void dfs(int x,int sum) {
//cout<
if(fl)return;
if(sum>ANS)return;
if(sum>f[x])return;
else f[x]=sum;
if(x==ed) {
if (ANS <= 2)
cout<2 <else cout<true;
}
for (int i=1; i<=5; i++) {
int tx=cha(x,i);
if(vis[tx])continue;
vis[tx]=true;
dfs(tx,sum+1);
vis[tx]=false;
}
}
深度优先搜索部分;
如果当前解大于已经找到的最优解,就切断这一分支路线。
如果当前x的解大于上次找到的x的解,也切断这一分支路线。
逐个交换x相邻的两位,产生新的状态,并标记、继续搜索。
以下是主函数:
int main() {
//freopen("2133.in","r",stdin);
memset(vis,0,sizeof(vis));
st=qread();
ed=qread();
if(st==ed) {
cout<<2<return 0;
}
for (int i=1; iwhile (true) {
if(fl)break;
ANS++;
dfs(st,0);
}
return 0;
}
初始化vis和f数组,枚举ans值