Description
Given two positive integersNAndK, You are asked to generate a new integer, sayM, By changing some (maybe none) digitsN, Such that the following properties holds:
- MContains no leading zeros and has the same lengthN(We considerZeroItself a one-digit integer without leading zeros .)
- MIs divisibleK
- Among all numbers satisfying properties 1 and 2,MWocould be the one with least number of digits different fromN
- Among all numbers satisfying properties 1, 2 and 3,MWocould be the smallest one
Input
There are multiple test cases for the input. Each test case consists of two lines, which containsN(1 ≤N≤ 10100) andK(1 ≤K≤ 104,K≤N) For each line. BothNAndKWill not contain leading zeros.
Output
Output one line for each test case containing the desired numberM.
Sample Input
226191033219
Sample output
2119103
See a blog explained in very detail, Here reference, portal: http://blog.csdn.net/lyy289065406/article/details/6698787/
# Include <stdio. h> # include <string. h ># include <algorithm> using namespace STD; char s [105]; int DP [105] [10], TEM [105], a [105], Mod, Len, f [105] [10005], K; void Init () {int I, j; for (I = 0; I <= 9; I ++) DP [1] [I] = I % MOD; for (I = 2; I <= Len; I ++) for (j = 0; j <= 9; j ++) DP [I] [J] = (DP [I-1] [J] * 10) % MOD; memset (F, 0, sizeof (f ));} bool DFS (int cnt, int L, int K) // start from L and change CNT numbers to 0 {int I, j; If (! K) {for (I = 0; I <Len; I ++) printf ("% d", TEM [I]); printf ("\ n "); return 1;} If (! CNT) return 0; If (L> len-1) return 0; If (F [l] [k]> = CNT) return 0; for (I = L; I <Len; I ++) // starting from the high position, take {for (j = 0; j <A [I]; j ++) {If (! I &&! J) continue; TEM [I] = J; int temp = (k-DP [Len-I] [A [I] + dp [Len-I] [J]) % MOD; If (temp <0) temp + = MOD; If (DFS (cnt-1, I + 1, temp) return 1 ;} TEM [I] = A [I];} for (I = len-1; I> = L; I --) // low start, to increase {for (j = A [I] + 1; j <= 9; j ++) {If (! I &&! J) continue; TEM [I] = J; int temp = (k-DP [Len-I] [A [I] + dp [Len-I] [J]) % MOD; If (temp <0) temp + = MOD; If (DFS (cnt-1, I + 1, temp) return 1 ;} TEM [I] = A [I];} f [l] [k] = CNT; // The number of CNT records starting with l cannot change K to 0 return 0 ;} int main () {int I, j; while (~ Scanf ("% s", S) {scanf ("% d", & mod); Len = strlen (s); Init (); k = 0; for (I = 0; I <Len; I ++) TEM [I] = A [I] = s [I]-'0'; for (I = len-1; i> = 0; I --) k = (k + dp [Len-I] [A [I]) % MOD; for (I = 0; I <Len; I ++) if (DFS (I, 0, k) break;} return 0 ;}