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): Fig 1 Digits from 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 ( n 100)
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.
用dp[i][j]表示i位数余j,需要的最少火柴数。通过枚举在后面填上一个数进行刷表更新。
求出dp数组之后,从大到小每一位尽量填大的,只要让剩下的火柴数足以在后面拼出满足要求的余数即可。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int dp[110][3010],pow[110],cost[]={6,2,5,5,4,5,6,3,7,6},m,n;
int left(int plc,int md,int x)
{
return ((md-x*pow[plc-1]%m)%m+m)%m;
}
int main()
{
int i,j,k,p,q,x,y,z,K=0,md,temp;
while (scanf("%d%d",&n,&m)==2)
{
printf("Case %d: ",++K);
pow[0]=1;
for (i=1;i<=n;i++)
pow[i]=pow[i-1]*10%m;
memset(dp,0x3f,sizeof(dp));
dp[0][0]=0;
for (i=0;i<n;i++)
for (j=0;j<m;j++)
for (x=0;x<=9;x++)
dp[i+1][(j*10+x)%m]=min(dp[i+1][(j*10+x)%m],dp[i][j]+cost[x]);
for (i=n;i;i--)
if (dp[i][0]<=n) break;
if (i==0)
{
printf("-1\n");
continue;
}
for (md=0;i;i--)
for (j=9;j>=0;j--)
if (dp[i-1][temp=left(i,md,j)]+cost[j]<=n)
{
printf("%d",j);
md=temp;
n-=cost[j];
break;
}
printf("\n");
}
}