Changing Digits
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 2717 | Accepted: 863 |
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
Source
POJ Monthly--2007.09.09, Rainer
此题不会做看的解题报告做的,但仍是错了很多遍。
此题不会做看的解题报告做的,但仍是错了很多遍。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#define N 101
#define M 10010
using namespace std;
char s1[N];
int t_mod[N][10],ori[N],get[N],l,check[N][M],m;
int main()
{
//freopen("data.in","r",stdin);
bool dfs(int sum,int pos,int mod);
while(scanf("%s",s1)!=EOF)
{
scanf("%d",&m);
l = strlen(s1);
for(int i=0;i<=9;i++)
{
t_mod[0][i] = i%m;
}
for(int i=1;i<=l-1;i++)
{
for(int j=0;j<=9;j++)
{
t_mod[i][j] = (10 * t_mod[i-1][j])%m;
}
}
int mod = 0;
for(int i=0;i<=l-1;i++)
{
get[i] = ori[i] = (s1[l-1-i]-'0');
mod += t_mod[i][get[i]];
mod = mod % m;
}
memset(check,0,sizeof(check));
for(int i=0;i<=l;i++)
{
if(dfs(i,l-1,mod))
{
break;
}
}
}
return 0;
}
bool dfs(int sum,int pos,int mod)
{
if(mod==0)
{
for(int i=l-1;i>=0;i--)
{
printf("%d",get[i]);
}
printf("\n");
return true;
}
if(check[sum][mod]>pos||sum==0)
{
return false;
}
for(int i=pos;i>=0;i--)
{
for(int j=0;j<ori[i];j++)
{
if(i==l-1&&j==0)
{
continue;
}
int vi_mod = (t_mod[i][j] + mod - t_mod[i][ori[i]])%m;
if(vi_mod<0)
{
vi_mod += m;
}
get[i] = j;
if(dfs(sum-1,i-1,vi_mod))
{
return true;
}
}
get[i] = ori[i];
}
for(int i=0;i<=pos;i++)
{
for(int j=ori[i]+1;j<10;j++)
{
int vi_mod = (t_mod[i][j] + mod - t_mod[i][ori[i]])%m;
if(vi_mod<0)
{
vi_mod += m;
}
get[i] = j;
if(dfs(sum-1,i-1,vi_mod))
{
return true;
}
}
get[i] = ori[i];
}
check[sum][mod] = pos+1;
return false;
}