HDU 1195 Open the Lock【DFS】

3705 ワード


Open the Lock
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 5300    Accepted Submission(s): 2359
Problem 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

 
Author
YE, Kai
 
Source
Zhejiang University Local Contest 2005
 
タイトル:
1234を2144に変える
3つの変更方法があります
1:左右の2桁の交換数字例えば:1と2は1234を交換して2134になります
2:増加1   例えば、千位増加1 1234は2234になります
3:減少1   例えば:百位増加1 1234は1134になります
PS:数字が9の場合は1 9増加して1になる
        数字が1の場合  縮小1  1が9になる
注意:
1:11行でaa[]を定義する場合、13行のループは1から始まるのでaa[0]は0に定義する
#include<stdio.h>
#include<string.h>
int a[8],b[8],vis[8],min,sumstep;
int pos(int a)
{
    return a>=0?a:-a;
}
int st(int sum)//                   
{
    //   1        aa    a[0]   0
    int aa[5]= {0,sum/1000%10,sum/100%10,sum/10%10,sum/1%10};
    int minstep=0;
    for(int i=1; i<=4; i++)
    {
        if(pos(aa[i]-b[i])<5)
            minstep+=pos(aa[i]-b[i]);
        else
            minstep+=9-pos(aa[i]-b[i]);
    }
    return minstep;
}
void DFS(int sum,int change)
{
    if(sum>999)
    {
        sumstep=change+st(sum);//change           
        //printf ("sum     %d i %d change %d
2144
",sum,sumstep,change); if(min>sumstep) min=sumstep;// return ; } for(int i=1; i<=4; i++) { if(vis[i]==0) { vis[i]=1; //printf("change~%d
",change); DFS(sum*10+a[i],change++); //printf("change %d
",change); vis[i]=0; } } } int main(void) { int T,aa,bb; scanf("%d",&T); while(T--&&scanf("%d%d",&aa,&bb)) { int leng; for(int i=1,leng=1000; i<=4; i++,leng=leng/10) { a[i]=aa/leng%10; b[i]=bb/leng%10; } min=99999; DFS(0,0); printf("%d
",min); } return 0; }