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:
- 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
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
- POJ-3373 (DP)
- poj 3373 数论常识(数位dp)
- POJ 3373 Changing Digits(DP)
- poj 1160(dp)
- Poj 2229(dp)
- Poj 2385 (dp)
- Poj 3616 (dp)
- Poj 3280(dp)
- Poj 2392(dp)
- Poj 1631(dp)
- poj 3267(dp)
- Poj 3046(dp)
- POJ 3260(DP)
- poj 2151 (DP)
- POJ-2385(DP)
- POJ-2955(DP)
- POJ-3267(DP)
- poj 1157 (DP)
- git基本操作
- 欧几里得辗转相除求最大公约数最小公倍数
- final和static final之间的区别
- shell学习
- C++实验3—个人所得税计算器
- POJ-3373 (DP)
- Laxcus大数据管理系统2.0(3)- 第一章 基础概述 1.2 产品特点
- Java基础知识
- 九度oj 题目1202:排序 题解
- Error C2662
- Java-单机版的书店管理系统(练习设计模块和思想_系列 五 )
- 描述TCP 协议三次握手,四次释放的过程
- 你足够了解Context吗?
- Thread.isAlive()