The main topic: give two strings of length n (n<=1000) only a string of numbers, each operation can be a continuous 1 to 3 digital modulo 10 plus 1 or modulo 10 minus 1 (i.e., 9+1=0,0-1=9), the minimum number of steps to find the source string can become the target string.
First, assume that for any operation, the last operand is treated as the operand of the operation. For example, 0001 steps into 111 operands as a 3rd number.
Preprocessing Array Cost,cost[i][j] represents the minimum number of steps (i,j<1000) from the number I to the number J if only the last number is the operand. For example, 111 to 220 is 3, only the last number can be manipulated, so 111-->222->221-->220.
Use A[i] and b[i] to represent the number of the source string and the first digit of the target number string.
Use D[i][j] to denote the first I number, the first i-2 has become the target number, and the first i-1 and I are composed of the decimal number J case, the minimum number of steps required.
The recursion is done based on the state D[i-1][u "when the operand is complete before all operations are i-1 and i-1."
If the previous state is D[i-1][u] (at this point the number of the source string does not change), then the transfer is only the last number of operations, the three-digit u*10+a[i] into three-digit b[i-2]*100+j (in the state D[i][j], The number of i-2 has been converted to the target number, which is exactly what the cost array stores, thus completing the recursion.
State transition equation:
d[i][j]=min {D[i-1][u]+cost[q][p]}
where P=b[i-2]*100+j,q=u*10+a[i]
#include <stdio.h> #include <stdlib.h> #include <string.h>char a[1010];char b[1010];int d[2][110]; int Cost[1010][1010];int main (void) {int i,j,u,p,q,i1,i2,i3,j1,j2,j3,u1,u2,u3,lo,cur,minp;for (i=0;i<1000;i++) { for (j=0;j<1000;j++) {if (i!=j) {if (cost[j][i]>0) {cost[i][j]=cost[j][i];} Else{i1=i/100;i2= (i%100)/10;i3=i%10;j1=j/100;j2= (j%100)/10;j3=j%10;if (i1<j1) {u1=j1-i1;i2= (I2+U1)%10;i3= (i3+ U1)%10;} Else{u1=i1-j1;i2= (i2-u1+10)%10;i3= (i3-u1+10)%10;} if (i2<j2) {u2=j2-i2;i3= (I3+U2)%10;} else{u2=i2-j2;i3= (i3-u2+10)%10;} u3= (i3>j3)? i3-j3:j3-i3;u1= (U1>10-U1)? 10-u1:u1;u2= (U2>10-U2)? 10-u2:u2;u3= (U3>10-U3)? 10-u3:u3;cost[i ][j]=u1+u2+u3;}}}} while (scanf ("%s%s", a+1,b+1) ==2) {Lo=strlen (a+1), if (lo==1) {u= (a[1]>b[1])? A[1]-b[1]:b[1]-a[1];p rintf ("%d\n", (U >10-u)? 10-u:u);} Else{for (j=0;j<10;j++) {u= (j>a[1]-' 0 ')? j-a[1]+ ' 0 ': a[1]-' 0 '-j;d[0][j]= (u>10-u)? 10-u:u;} for (j=0;j<100;j++) {minp= (1<<30), for (u=0;u<10;u++) {q=u*10+a[2]-' 0 '; minp= (D[0][U]+COST[Q][J]<MINP )? d[0][U]+COST[Q][J]:MINP;} D[1][J]=MINP;} Cur=1;for (i=3;i<=lo;i++) {cur^=1;for (j=0;j<100;j++) {minp= (1<<29); for (u=0;u<100;u++) {p= (b[i-2]-' 0 ') *100+j;q=u*10+a[i]-' 0 '; minp= (D[CUR^1][U]+COST[P][Q]<MINP) d[cur^1][u]+cost[p][q]:minp;} D[CUR][J]=MINP;}} p= (b[lo-1]-' 0 ') *10+b[lo]-' 0 ';p rintf ("%d\n", D[cur][p]);}} return 0;}
UVA 1631-locker (DP)