POJ-3373 (DP)

来源:互联网 发布:python bloom filter 编辑:程序博客网 时间:2024/06/10 08:47
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 3240 Accepted: 1055

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

226191033219

Sample Output

2119103

Source

POJ Monthly--2007.09.09, Rainer

分析:DP做法,DP[I][J] 表示前I位模k等于J时最少改变几位数字,然后每次从0开始(除第N位外)枚举这位上的数字(保证答案最小),在DP的过程中记录下每次的决策即可。

#include <cstdio>#include <cstring>#include <iostream>using namespace std;int k,n,f[102][10],dp[102][10000],ans[102][10000],a[102];char s[102];int main(){while(cin >> s){n = strlen(s);cin >> k;for(int i = 1;i <= n;i++) a[i] = s[n-i]-'0';for(int j = 0;j <= 9;j++) f[1][j] = j % k; for(int i = 2;i <= n;i++) for(int j = 0;j <= 9;j++)    f[i][j] = f[i-1][j]*10 % k;  memset(dp,3,sizeof(dp));dp[0][0] = 0;  for(int i = 1;i <= n;i++) for(int j = 0;j < k;j++)  for(int now = i == n ? 1:0;now <= 9;now++)  {  int dt = now == a[i] ? 0:1;if(dp[i][j] > dp[i-1][(k+j-f[i][now])%k] + dt){dp[i][j] = dp[i-1][(k+j-f[i][now])%k] + dt;ans[i][j] = now;}   }int now = 0;    for(int i = n;i > 0;i--)    {    cout << ans[i][now];    now = (k+now-f[i][ans[i][now]]) % k;}cout << endl; } } 


0 0
原创粉丝点击