POJ3373:Changing Digits(记忆化)

Description

Given two positive integers n and k, you are asked to generate a new integer, say m, by changing some (maybe none) digits of n, such that the following properties holds:

  1. m contains no leading zeros and has the same length as n (We consider zero itself a one-digit integer without leading zeros.)
  2. m is divisible by k
  3. among all numbers satisfying properties 1 and 2, m would be the one with least number of digits different from n
  4. among all numbers satisfying properties 1, 2 and 3, m would be the smallest one

Input

There are multiple test cases for the input. Each test case consists of two lines, which contains n(1≤n≤10100) and k(1≤k≤104kn) for each line. Both n and k will not contain leading zeros.

Output

Output one line for each test case containing the desired number m.

Sample Input

2
2
619103
3219

Sample Output

2
119103
 
 
看到一篇博客解释的非常详细,在此引用一下,传送门:http://blog.csdn.net/lyy289065406/article/details/6698787/
 
 
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

char s[105];
int dp[105][10],tem[105],a[105],mod,len,f[105][10005],k;

void init()
{
    int i,j;
    for(i = 0; i<=9; i++)
        dp[1][i] = i%mod;
    for(i = 2; i<=len; i++)
        for(j = 0; j<=9; j++)
            dp[i][j] = (dp[i-1][j]*10)%mod;
    memset(f,0,sizeof(f));
}

bool dfs(int cnt,int l,int k)//从l开始,还要改变cnt个数字,使得余数k变为0
{
    int i,j;
    if(!k)
    {
        for(i = 0; i<len; i++)
            printf("%d",tem[i]);
        printf("\n");
        return 1;
    }
    if(!cnt) return 0;
    if(l>len-1) return 0;
    if(f[l][k]>=cnt) return 0;
    for(i = l; i<len; i++)//高位开始,从小取
    {
        for(j = 0; j<a[i]; j++)
        {
            if(!i && !j)
                continue;
            tem[i] = j;
            int temp = (k-dp[len-i][a[i]]+dp[len-i][j])%mod;
            if(temp<0)
                temp+=mod;
            if(dfs(cnt-1,i+1,temp))
                return 1;
        }
        tem[i] = a[i];
    }
    for(i = len-1; i>=l; i--)//低位开始,要变大
    {
        for(j = a[i]+1; j<=9; j++)
        {
            if(!i && !j)
                continue;
            tem[i] = j;
            int temp = (k-dp[len-i][a[i]]+dp[len-i][j])%mod;
            if(temp<0)
                temp+=mod;
            if(dfs(cnt-1,i+1,temp))
                return 1;
        }
        tem[i] = a[i];
    }
    f[l][k] = cnt;//l开始取cnt个数不能使得k变为0
    return 0;
}

int main()
{
    int i,j;
    while(~scanf("%s",s))
    {
        scanf("%d",&mod);
        len = strlen(s);
        init();
        k = 0;
        for(i = 0; i<len; i++)
            tem[i] = a[i] = s[i]-'0';
       for(i = len-1; i>=0; i--)
           k = (k+dp[len-i][a[i]])%mod;
        for(i = 0; i<len; i++)
            if(dfs(i,0,k))
                break;

    }

    return 0;
}


你可能感兴趣的:(dp,poj,DFS)