uva12105 Bigger is Better

175 篇文章 0 订阅
137 篇文章 0 订阅

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");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值