您的位置:首页 > 其它

POJ-3373 (DP)

2016-04-12 20:30 288 查看
Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 3240Accepted: 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:

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
分析: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: