HDU 1195 Open the Lock【DFS】

 

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

有三种改变方式

1:左右两位互换数字 如: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\n        2144\n",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\n",change);
            DFS(sum*10+a[i],change++);
            //printf("change %d\n",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\n",min);
    }
    return 0;
}


 

 

你可能感兴趣的:(ACM,HDU)