POJ-3373 (DP)
2016-04-12 20:30
288 查看
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 3240 | Accepted: 1055 |
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; } }
相关文章推荐
- 使Handler内部类不导致内存泄露的解决方法
- WCF服务如何获得客户端IP地址信息
- Struts---拦截器
- Laxcus大数据管理系统2.0(2)- 第一章 基础概述 1.1 基于现状的一些思考
- 微商城开发(2)
- 数据结构和算法03 之链表
- LIME:一种解释机器学习模型的方法
- DotNet基础
- 程序是用来解决问题的
- 【NodeJs】用arrayObject.join('')处理粘包的错误原因
- 排序算法---快速排序
- 给定日期-判断是星期几
- Properties Editor
- 【Bugly干货分享】iOS内存管理:从MRC到ARC实践
- Android layout_weight理解
- web开发-前端到服务器Controller中的数据传递
- Ruby Get Started
- 迷宫问题并求最短路径
- truncate file python
- 法律法规和标准规范