Bob has n matches. He wants to compose numbers using the following scheme (which is, digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 needs 6, 2, 5, 5, 4, 5 , 6, 3, 7, 6 matches): Fig 1 Digits from matches
Write a non-negative integer which is a multiple of M. The integer should be as big as possible. Input
The input consists of several test cases. Each case was described by the positive integers n (n100) and M (m3000), as described above. The last test case was followed by a single zero, which should wasn't be processed. Output
For each test case, print the case number and the biggest number, which can be made. If There is no solution, output-1. Note that Bob don ' t has to use any of his matches. Sample Input
6 3
5) 6
0
Sample Output
Case 1:111 Case
2:1
n A match can make up the largest number divisible by M.
DP[I][J] means that the largest number of M-J is divisible by the I match, V[k] represents the number of matches to be composed of K, dp[i+v[k]][(j*10+k)%m]=max (dp[i+v[k]][(j*10+k)%m],dp[i][j]*10+k), We generally loop to calculate the DP is the state from the previous calculation to update the current state, and this is to take the current state to update the back of the state, is actually the same, to the current state of the time it has been in front of all can update its update. And the advantage of this problem is that i+v[k] the remainder of the match is (J*10+k)%M, and if the remainder of i-v[k] is not good to forget.
This problem may have 50 digits, which should be used in large numbers. The book said it can not be large numbers, this is really not thought out how to get.
#include <cstring> #include <cstdio> #include <iostream> #include <climits> #include <cmath > #include <algorithm> #include <queue> #include <map> #define INF 0x3f3f3f3f #define MAXN #define
MAXM 3010 using namespace std;
int n,m;
int v[10]={6,2,5,5,4,5,6,3,7,6};
Char dp[maxn][maxm][60],ans[60],s[60];
int compare (char *a,char *b) {int La=strlen (a), Lb=strlen (b);
if (la>lb) return 1;
else if (la<lb) return-1;
Return strcmp (A, b);
} void DP (char *a,char *b,int k) {strcpy (s,b);
int L=strlen (s);
if (l==1&&s[0]== ' 0 ') {s[l-1]= ' 0 ' +k;
s[l]=0;
} else{s[l]= ' 0 ' +k;
s[l+1]=0;
} if (compare (s,a) >0) strcpy (a,s);
} int main () {//freopen ("In.txt", "R", stdin);
int cas=0;
while (scanf ("%d", &n), N) {scanf ("%d", &m);
Memset (Dp,0,sizeof (DP));
dp[0][0][0]= ' 0 '; for (int i=0;i<=n;i++) for (int j=0;j<m;j++) if (strlen (dP[I][J]) >0) {for (int k=0;k<10;k++) DP (dp[i+v[k]][(j*10+k)%m],dp[i][j],k);
} ans[0]=0;
for (int i=n;i>0;i--) if (compare (ans,dp[i][0)) <0) strcpy (ans,dp[i][0]);
printf ("Case%d:", ++cas);
if (ans[0]==0) puts ("-1");
Else puts (ans);
} return 0;
}