题意:给你两个只包含数字1~6的长度不超过110的字符串a和b,两种操作:
1、把b中某一位b[i]改成j
2、把b中的数字i都改成j
求b串改成a串所需的最小步数。
思路:
bfs。其实可以想到,可以忽略长度,直接考虑第二种操作的情况。因为第二种操作数越多,我们才有可能使总步数变少。
所以直接bfs预处理123456能变成的所有情况所需的最少第二操作数,然后剩下的和a串不同的一个一个改,取最小值即可。
代码:
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=120;
int dp[800010];
char s1[maxn],s2[maxn];
int tmp[10],cnt,id[1000010],stp[1000010];
int a[maxn],c[maxn];
void bfs()
{
tmp[7]=cnt=1;
for(int i=6;i>=1;i--) tmp[i]=tmp[i+1]*10;
queue<int>q;
q.push(123456);
for(int i=0;i<=666666;i++) dp[i]=inf;
dp[123456]=0;
id[cnt]=123456;
stp[cnt]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
for(int i=1;i<=6;i++)
for(int j=1;j<=6;j++)
if(i!=j)
{
int xx=0;
for(int k=1;k<=6;k++)
{
xx*=10;
int l=(x%tmp[k])/tmp[k+1];
if(l==i) xx+=j;
else xx+=l;
}
if(dp[x]+1<dp[xx])
{
dp[xx]=dp[x]+1;
id[++cnt]=xx;
stp[cnt]=dp[xx];
q.push(xx);
}
}
}
}
void solve()
{
int ans=inf,len=strlen(s1);
for(int i=1;i<=cnt;i++)
{
for(int j=0;j<len;j++)
a[j]=(s2[j]&15);
for(int j=1;j<=6;j++)
c[j]=(id[i]%tmp[j])/tmp[j+1];
for(int j=0;j<len;j++)
a[j]=c[a[j]];
int sum=0;
for(int j=0;j<len;j++)
if(a[j]!=(s1[j]&15)) sum++;
ans=min(ans,sum+stp[i]);
}
printf("%d\n",ans);
}
int main()
{
bfs();
while(scanf("%s%s",s1,s2)!=EOF) solve();
return 0;
}