Bob has n matches. He wants to compose numbers using the following scheme (that is, digit 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 needs 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 matches):

Write a program to make 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 is described by two positive integers n (n100) and m (m
3000) ,
as described above. The last test case is followed by a single zero, which should not be processed.
Output
For each test case, print the case number and the biggest number that can be made. If there is no solution, output -1. Note that Bob don't have to use all his matches.
Sample Input
6 3 5 6 0
Sample Output
Case 1: 111 Case 2: -1
题意:用n跟火柴组成一个能被m整除的最大的数。
思路:dp[i][j]表示用i根火柴被m整除余数为j的最大数,下一个状态为dp[i+num[k]][(j*10+k)%m]。注意可以有剩下的火柴。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
char s[55];
}dp[110][3010];
int n,m,num[10]={6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
bool CAM(int a,int b,int c,int d)
{
int len1=strlen(dp[a][b].s),len2=strlen(dp[c][d].s);
if(len1>len2)
return true;
if(len2>len1)
return false;
return strcmp(dp[a][b].s,dp[c][d].s)>0;
}
int main()
{
int i,j,k,len,t=0;
while(~scanf("%d",&n)&& n)
{
scanf("%d",&m);
for(i=0;i<=n;i++)
for(j=0;j<=m;j++)
dp[i][j].s[0]='\0';
dp[0][0].s[0]='0';dp[0][0].s[1]='\0';
for(i=0;i<=n;i++)
for(j=0;j<m;j++)
if(dp[i][j].s[0]!='\0')
{
len=strlen(dp[i][j].s);
for(k=0;k<=9;k++)
{
if(i+num[k]>n)
continue;
if(dp[i][j].s[0]=='0')
dp[i][j].s[0]='0'+k;
else
{
dp[i][j].s[len]='0'+k;dp[i][j].s[len+1]='\0';
}
if(CAM(i,j,i+num[k],(j*10+k)%m))
strcpy(dp[i+num[k]][(j*10+k)%m].s,dp[i][j].s);
if(dp[i][j].s[len]!='\0')
dp[i][j].s[len]='\0';
else
dp[i][j].s[len-1]='0';
}
}
for(i=1;i<=n;i++)
if(dp[i][0].s[0]!='\0' && CAM(i,0,0,1))
strcpy(dp[0][1].s,dp[i][0].s);
printf("Case %d: ",++t);
if(dp[0][1].s[0]=='\0')
printf("-1\n");
else
printf("%s\n",dp[0][1].s);
}
}