您的位置:首页 > 运维架构

Open the Lock

2013-03-28 12:50 309 查看
[align=left]Problem Description[/align]
Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9. Each time, you can add or minus 1 to any digit. When add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9'. You can also exchange the digit with its neighbor. Each action will take one step.
Now your task is to use minimal steps to open the lock.
Note: The leftmost digit is not the neighbor of the rightmost digit.

[align=left]Input[/align]
The input file begins with an integer T, indicating the number of test cases.
Each test case begins with a four digit N, indicating the initial state of the password lock. Then followed a line with anotther four dight M, indicating the password which can open the lock. There is one blank line after each test case.

[align=left]Output[/align]
For each test case, print the minimal steps in one line.

[align=left]Sample Input[/align]

2
1234
2144

1111
9999

[align=left]Sample Output[/align]

2
4

#include<iostream>
#include<queue>
#include<string.h>
#include<string>
using namespace std;
int a[4];
int end[4];
struct lmx{
int x;
int temp;
};
void fac(int x,int a[])
{
int i;
for(i=3;i>=0;i--)
{
a[i]=x%10;
x/=10;
}
}
void inc_dec(int a[],int t)
{
int j;
j=t/2;
if(t%2==0)
{
if(a[j]==9) a[j]=1;
else a[j]+=1;
}
else
{
if(a[j]==1) a[j]=9;
else a[j]-=1;
}
}
void exchange(int a[],int i)
{
int temp;
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
int cnt(int a[])
{
int i,val=0;
for(i=0;i<4;i++)
{
val=val*10+a[i];
}
return val;
}
queue<lmx>q;
int hash[10000],ea;
lmx s1,s2,s3;
int bfs()
{
int i;
while(!q.empty()) q.pop();
q.push(s1);
if(s1.x==ea) return 0;
while(!q.empty())
{
s2=q.front();
q.pop();
for(i=0;i<11;i++)
{
fac(s2.x,a);
if(i<8)
{
inc_dec(a,i);
}
else
{
exchange(a,i-8);
}
s3.x=cnt(a);
s3.temp=s2.temp+1;
if(s3.x==ea) return s3.temp;
if(hash[s3.x]==0) {q.push(s3);hash[s3.x]=1;}
}
}
return 0;
}
int main()
{
int ca,i,ends,sa;
cin>>ca;
string ss,sp;
while(ca--)
{
cin>>ss;
for(i=0;i<4;i++) a[i]=ss[i]-'0';
s1.temp=0;
sa=cnt(a);
s1.x=sa;
hash[sa]=1;
cin>>sp;
for(i=0;i<4;i++) end[i]=sp[i]-'0';
ea=cnt(end);
memset(hash,0,sizeof(hash));
cout<<bfs()<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: