hdu 1195 Open tne Lock - 搜索

Description

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.

 

Input

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.

 

Output

For each test case, print the minimal steps in one line.

 

Sample Input

2

1234 2144 1111 9999

Sample Output

2

4

 

思路:

这题运用搜索的方法,对于一个状态,下一步有11种情况:第一位+1/-1,第二位+1/-1,第三位+1/-1,第四位+1/-1,一二位交换,二三位交换,三四位交换。把这些情况建立一个队列。因为情况比较多,每种情况要比较仔细,不要写错变量。

 

源代码:

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     int n,a,b,c,d,e,f,x,y,n_b;//x是可以存几个2*2,y是可以存几个1*1
 7     int s_2[4]={0,5,3,1};//3*3的可以放几个2*2
 8     int s_1[4]={0,7,6,5};//3*3的可以放几个1*1
 9     while(1)
10     {
11         scanf("%d %d %d %d %d %d",&a,&b,&c,&d,&e,&f);
12         if(a+b+c+d+e+f==0) break;
13         n=f+e+d+(c+3)/4;//  (c+3)/4向上取整
14         x=d*5+s_2[c%4];
15         if(x<b)//已有的箱子不够放2*2
16             {
17             n_b=(b-x+8)/9;//还需的箱子
18             n=n_b+n;
19             y=e*11+s_1[c%4]+n_b*36-(b-x)*4;
20             }
21             else
22             y=e*11+s_1[c%4]+(x-b)*4;
23         if(y<a) //剩余的空位不够放1*1
24           n+=(a-y+35)/36;
25     printf("%d\n",n);
26     }
27     return 0;
28 }

 

 

 

posted @ 2013-08-06 00:24  小の泽  阅读(177)  评论(0编辑  收藏  举报