uva12105 - Bigger is Better 大数

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 (n100) and m (m3000), 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的最大的数,v[k]表示组成数字k要几个火柴,dp[i+v[k]][(j*10+k)%M]=max(dp[i+v[k]][(j*10+k)%M],dp[i][j]*10+k),我们一般循环算dp的时候都是从前面算出的状态来更新当前状态,而这个是拿当前状态去更新后面的状态,其实是一样的,到当前状态的时候它已经被前面所有能更新它的更新过。而且这个题这样做的好处在于i+v[k]个火柴的余数就是(j*10+k)%M,而如果i-v[k]的余数就不好算了。

  这个题可能有50位数,要用大数。书上说可以不用大数,这个还真没想出来怎么弄。。

#include<cstring>
#include<cstdio>
#include<iostream>
#include<climits>
#include<cmath>
#include<algorithm>
#include<queue>
#include<map>
#define INF 0x3f3f3f3f
#define MAXN 110
#define MAXM 3010
using namespace std;
int N,M;
int v[10]={6,2,5,5,4,5,6,3,7,6};
char dp[MAXN][MAXM][60],ans[60],s[60];
int compare(char *a,char *b){
    int la=strlen(a),lb=strlen(b);
    if(la>lb) return 1;
    else if(la<lb) return -1;
    return strcmp(a,b);
}
void DP(char *a,char *b,int k){
    strcpy(s,b);
    int l=strlen(s);
    if(l==1&&s[0]=='0'){
        s[l-1]='0'+k;
        s[l]=0;
    }
    else{
        s[l]='0'+k;
        s[l+1]=0;
    }
    if(compare(s,a)>0) strcpy(a,s);
}
int main(){
    //freopen("in.txt","r",stdin);
    int cas=0;
    while(scanf("%d",&N),N){
        scanf("%d",&M);
        memset(dp,0,sizeof(dp));
        dp[0][0][0]='0';
        for(int i=0;i<=N;i++)
            for(int j=0;j<M;j++) if(strlen(dp[i][j])>0){
                for(int k=0;k<10;k++) DP(dp[i+v[k]][(j*10+k)%M],dp[i][j],k);
            }
        ans[0]=0;
        for(int i=N;i>0;i--) if(compare(ans,dp[i][0])<0) strcpy(ans,dp[i][0]);
        printf("Case %d: ",++cas);
        if(ans[0]==0) puts("-1");
        else puts(ans);
    }
    return 0;
}



你可能感兴趣的:(uva12105 - Bigger is Better 大数)