POJ-3373 (DP)

116 篇文章 0 订阅
96 篇文章 0 订阅
Time Limit: 3000MS Memory Limit: 65536K
Total 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

2
2
619103
3219

Sample Output

2
119103

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值