Bigger is Better - UVa 12105 dp

本文介绍了一道算法题目,要求使用给定数量的火柴棒构造出一个尽可能大的正整数,该整数还需满足能被特定数值整除。通过动态规划方法,实现了高效的求解算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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):

\epsfbox{p3782.eps}

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$ \le$100) and m (m$ \le$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);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值