首页 > 代码库 > POJ3373:Changing Digits(记忆化)
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:
- m contains no leading zeros and has the same length as n (We consider zero itself a one-digit integer without leading zeros.)
- m is divisible by k
- among all numbers satisfying properties 1 and 2, m would be the one with least number of digits different from n
- 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≤104, k≤n) 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。