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 (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.
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][(j*10+k)%m]=min(dp[i][(j*10+k)%m],dp[i-1][j]+cnt[k])。
枚举找出能获得的最高的位数。然后从高位开始枚举,比如已知最高位数为3,m=7。先令这个数为9xx,900%m=4(X00...%m要先预处理),如果dp[2][m-4]<=n-cnt[9],则这一位可以为9,若不能再枚举8。以此类推。
//
// main.cpp
// 123
//
// Created by zyh on 16/7/27.
// Copyright © 2016年 zyh. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
using namespace std;
int n,m;
int cnt[10]= {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
int dp[105][3005]; //i位数字,除m余j时最少需要多少根火柴
int ans[105];
int mod[10][105]; //数字i,后面j个0,组成的数字膜m的值
void dfs(int pos, int x, int sum)
{
if(pos==0)
return ;
for(int i=9; i>=0; i--)
{
for(int t=0; t<m; t++)
{
if((t+mod[i][pos])%m==x)
{
if(cnt[i]+dp[pos-1][t]<=sum)
{
printf("%d", i);
dfs(pos-1, t, sum-cnt[i]);
return ;
}
}
}
}
}
int main()
{
int cas=1;
while(cin>>n)
{
if(n==0) break;
cin>>m;
cout<<"Case "<<cas++<<": ";
memset(dp,0x3f3f3f,sizeof(dp));
dp[0][0]=0;
for(int i=0;i<=9;i++) //预处理一位数的情况
{
dp[1][i%m]=min(cnt[i],dp[1][i%m]);
}
for(int i=2;i<=n/2;i++)
{
for(int j=0;j<m;j++)
{
for(int k=0;k<=9;k++)
{
dp[i][(j*10+k)%m]=min(dp[i][(j*10+k)%m],dp[i-1][j]+cnt[k]);
}
}
}
int weishu=0;
for(int i=n/2;i>=1;i--) //求出能组成的数字的最大位数
{
if(dp[i][0]<=n)
{
weishu=i;
break;
}
}
if(weishu==0)
{
cout<<-1<<endl;
continue;
}
memset(mod,0,sizeof(mod));
for(int i=0;i<=9;i++) //预处理X00...%m
{
mod[i][0]=i%m;
for(int j=1;j<=100;j++)
{
mod[i][j]=mod[i][j-1]*10%m;
}
}
int temp=0;
while(weishu>0)
{
for(int i=9;i>=0;i--) //从最高位枚举
{
if(dp[weishu-1][(m+temp-mod[i][weishu-1])%m]<=n-cnt[i])
{
cout<<i;
n-=cnt[i];
temp=(m+temp-mod[i][weishu-1])%m;
break;
}
}
weishu--;
}
cout<<endl;
}
return 0;
}