HDU 1195.Open the Lock

230


题目



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


题解



变相的BFS,交换的次数为层数3

遍历所有交换的可能,计算每种可能下,距离答案的“距离”

代码



/*
By:OhYee
Github:OhYee
Email:oyohyee@oyohyee.com
Blog:http://www.cnblogs.com/ohyee/

かしこいかわいい?
エリーチカ!
要写出来Хорошо的代码哦~
*/

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
using namespace std;

//DEBUG MODE
#define debug 0

//循环
#define REP(n) for(int o=0;o<n;o++)

int del(int a,int b) {
int cnt = 0;
while (a) {
int t1 = (a % 10);
int t2 = (b % 10);
cnt += abs(t1-t2)>4?(9 - abs(t1 - t2)): abs(t1 - t2);
a /= 10;
b /= 10;
}
return cnt;
}

int Swap(int s,int a,int b) {
int t[4] = {0};
for (int i = 3;i >= 0;i--) {
t[i] = s % 10;
s /= 10;
}
swap(t[a],t[b]);
return t[0] * 1000 + t[1] * 100 + t[2] * 10 + t[3];
}

int BFS(int s,int v) {
int Min = del(s,v);
bool visited[9999];
memset(visited,false,sizeof(visited));

queue<pair<int,int> > Q;
Q.push(pair<int,int>(s,0));
visited[s] = true;
while (!Q.empty()) {
int k = Q.front().first;
int n = Q.front().second;
Q.pop();

for (int i = 0;i < 3;i++) {
int kk = Swap(k,i,i + 1);
int nn = n + 1;
if (visited[kk])
continue;
visited[kk] = true;
Min = min(nn + del(kk,v),Min);
//printf(" %d %d+%d=%d\n",kk,nn,del(kk,v),nn + del(kk,v));
Q.push(pair<int,int>(kk,nn));
}
}
return Min;
}

bool Do() {
int s,v;
scanf("%d%d",&s,&v);

printf("%d\n",BFS(s,v));

return true;
}

int main() {
int T;
scanf("%d",&T);
while (T--)
Do();
return 0;
}
发布评论
  • 点击查看/关闭被识别为广告的评论