题目链接:https://vjudge.net/problem/HihoCoder-1426
转自:https://blog.csdn.net/xianpingping/article/details/82940242
题意:有一个数字序列,有三种操作:1.交换两个数字 2.将一个数字加1 3.将一个数字*2。其中操作2有3次,操作3有两次。问能够变成12345的最小步数。
思路:bfs预处理。直接用12345看能够到达哪些状态即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn=100005;
int res[maxn][5][5];
const int inf=0x3f3f3f3f;
struct NODE
{
int a[10],sec,thr,step;
bool operator <(const NODE &a)const
{
return step>a.step;
}
};
int trans(NODE a)
{
int cnt=a.a[1];
for(int i=2; i<=5; i++)
{
cnt*=10;
cnt+=a.a[i];
}
return cnt;
}
void bfs(NODE a)
{
res[12345][3][2]=0;
priority_queue <NODE> q;
q.push(a);
while(!q.empty())
{
NODE u=q.top();
q.pop();
NODE temp;
for(int i=2; i<=5; i++)
{
temp=u;
temp.step++;
swap(temp.a[i],temp.a[i-1]);
int cnt=trans(temp);
if(res[cnt][temp.sec][temp.thr]<=temp.step)
{
continue;
}
res[cnt][temp.sec][temp.thr]=temp.step;
q.push(temp);
}
if(u.sec>0)
{
for(int i=1; i<=5; i++)
{
temp=u;
temp.sec--;
temp.step++;
temp.a[i]=(temp.a[i]+1)%10;
int cnt=trans(temp);
if(temp.step>=res[cnt][temp.sec][temp.thr])
continue;
res[cnt][temp.sec][temp.thr]=temp.step;
q.push(temp);
}
}
if(u.thr>0)
{
for(int i=1; i<=5; i++)
{
temp=u;
temp.thr--;
temp.step++;
temp.a[i]=(temp.a[i]*2)%10;
int cnt=trans(temp);
if(temp.step>=res[cnt][temp.sec][temp.thr])
continue;
res[cnt][temp.sec][temp.thr]=temp.step;
q.push(temp);
}
}
}
}
int main()
{
NODE now;
now.sec=3;
now.thr=2;
now.step=0;
for(int i=1; i<=5; i++)
{
now.a[i]=i;
}
memset(res,inf,sizeof(res));
bfs(now);
int n;
while(~scanf("%d",&n))
{
int ans=inf;
for(int i=0; i<=3; i++)
{
for(int j=0; j<=2; j++)
{
ans=min(res[n][i][j],ans);
}
}
if(ans==inf)
ans=-1;
printf("%d\n",ans);
}
}