您的位置:首页 > 其它

12105 - Bigger is Better

2015-07-14 21:00 274 查看
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.

Sample Input

6 3

5 6

0

Sample Output

Case 1: 111

Case 2: -1

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn=100+5;
const int maxm=3000+5;
const int needs[]={6,2,5,5,4,5,6,3,7,6};
int n,m,dp[maxn][maxm],p[maxn][maxm];
//dp[i][j]存储用i根火柴得到除以m余数为j所能表示数的最大位数,p[i][j]表示得到该数最左边那位上的数
int main()
{
int T=0;
while(scanf("%d%d",&n,&m)==2&&n)
{
printf("Case %d: ",++T);
for(int i=0;i<=n;i++)
{
for(int j=0;j<m;j++)
{
int& ans=dp[i][j];
ans=p[i][j]=-1;
if(j==0)ans=0;
for(int d=9;d>=0;d--)
{
if(i>=needs[d]){
int t=dp[i-needs[d]][(j*10+d)%m];
/*
1.首先我们要明确一点,我们是先假设状态d(i,j)用i根火柴可以排出的数除以m的余数为j。假设!假设!如果没办法那么就会是-1;
2.d放入的位置应当是[1……]d[2……],所以余数应该是(j*10+d)%m;在d之前还有数,且余数已知(假设)。
3.[i-needs[d]]是相对[2……]而言的,还有i-needs[d]根火柴,余数是相对[1……]d而言的。
4.t+1应当是d[2……]的长度。
5.处理到最后[0]d[2……],d前面可以看成0;
6.可以参照一下下面给出的一个输出调试过程*/
if(t>=0&&t+1>ans){
ans=t+1;
p[i][j]=d;
}
}
}
}
}
if(p
[0]<0)printf("-1");
else{
int i=n,j=0;
for(int d=p[i][j];d>=0;d=p[i][j])
{

printf("%d",d);
/*printf("%d %d %d %d\n",d,j*10+d,(j*10+d)%m,dp[i-needs[d]][(j*10+d)%m]);
12 4
Case 1: 7 7 3 3
1 31 3 2
1 31 3 1
2 32 0 0

*/
i=i-needs[d];
j=(j*10+d)%m;
}
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: