题意:有一个n(n≤1000)位密码锁,每位都是0~9,可以循环旋转。每次可以让1~3个相邻 数字同时往上或者往下转一格。例如,567890->567901(最后3位向上转)。输入初始状态 和终止状态(长度不超过1000),问最少要转几次。例如,111111到222222至少转2次,由 896521到183995则要转12次。
分析:分成两种情况向上转和向下转,题目说可以同时转1~3,所以不用担心转多要回溯之类的,直接从头部枚举到尾部。确定了方向,就开始枚举后两位的转动次数,i+1位<=i,i+2<=i+1,这里面是转动次数的比较。
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<sstream>
#include<cassert>
#include<set>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int maxn = 1000+10;
int a[maxn], b[maxn];
char s1[maxn], s2[maxn];
int d[maxn][10][10][10];
int len;
int dp(int cur, int x, int y, int z) {
if (cur >= len )return 0;
int &ans = d[cur][x][y][z];
if (ans != -1)return ans;
ans = INF;
int t;
if (x <= b[cur])
t = b[cur] - x;
else
t = b[cur] + 10 - x;
for (int j = 0; j <= t; j++) {
for (int k = 0; k <= j; k++) {
ans = min(ans, dp(cur + 1, (y + j) % 10, (z + k) % 10, a[cur + 3]) + t);
}
}
if (x >= b[cur])
t = x - b[cur];
else
t = 10 - (b[cur]-x);
for (int j = 0; j <= t; j++) {
for (int k = 0; k <= j; k++) {
ans = min(ans, dp(cur + 1, (y - j + 10) % 10, (z - k + 10) % 10, a[cur + 3]) + t);
}
}
return ans;
}
int main() {
while (cin>>s1>>s2) {
memset(d, -1, sizeof(d));
len = strlen(s1);
for (int i = 0; i < len; i++) {
a[i] = s1[i] - '0';
b[i] = s2[i] - '0';
}
a[len] = a[len + 1] = b[len] = b[len + 1]=0;
cout << dp(0, a[0], a[1], a[2]) << endl;
}
return 0;
}