lishenghan 发表于 2019-1-27 08:25:42

HDU1195 Open the Lock

                                                      Open the Lock
Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2919    Accepted Submission(s): 1276


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 21441111 9999

   

Sample Output
2 4

   

Author
YE, Kai
   

Source
Zhejiang University Local Contest 2005
   

Recommend
Ignatius.L


解题思路:该题为广度优先搜索题,咋的一看可能想不到。但确实是求最短路劲的,不过和一般的迷宫搜索的方向不一样。这里的搜索树是根据题意走的,不是上下左右,而是加,减,左换,右换。始终记住广度优先搜索的特点,最短路径,遍历标记。一定要对搜索过得状态进行标记,不然等待的结果将是:超时。望大家以我为前车之鉴。。。。。。


#include #include #include #include using namespace std; int a; int b; int f; struct node {   int x;   int step; }; int bfs() {   int i,j;   node s,e;   queue q;   memset(f,0,sizeof(f));   s.x=a;   s.x=a;   s.x=a;   s.x=a;   s.step=0;   q.push(s);   //int n=20;   f]]]]=1;   while(!q.empty())   {         s=q.front();         q.pop();         if(s.x==b&&s.x==b&&s.x==b&&s.x==b)             return s.step;         //printf("%d%d%d%d\n",s.x,s.x,s.x,s.x);         for(i=0;i
页: [1]
查看完整版本: HDU1195 Open the Lock