【URAL 1658】1658. Sum of Digits(DP)
来源:互联网 发布:薛之谦 淘宝店 编辑:程序博客网 时间:2024/04/29 09:26
【URAL 1658】1658. Sum of Digits(DP)
题目大意:
定义s1为n的每位数字的加和。
s2为n的每位数字的平方和。
给出s1,s2,输出最小的n。如果不存在或者长度超过100,输出No solution。
dp[i][j]表示加和为i,平方和为j的最短长度。
预处理出来所有的加和和平方和的组合,然后存一下每个最小转移添加的数字。
因为长度超过100输出No solution。所以s1 > 900的直接pass。dp数组的第一维就可以变成901。
然后对于每个输入递归输出。
需要注意的是转移的时候如果有多个最优转移,存数字较小的。
for(int k = 1; k <= 9 && i-k >= 0 && j-k*k >= 0; ++k){ if(dp[i][j] > dp[i-k][j-k*k]+1)//大于号而不是大于等于! { dp[i][j] = dp[i-k][j-k*k]+1; ned[i][j] = k; }}
因为对于相同长度的n,高位越小,n越小,所以递归的时候从高位开始填数,优先添较小的数。
代码如下:
#include <iostream>#include <cmath>#include <vector>#include <cstdlib>#include <cstdio>#include <climits>#include <ctime>#include <cstring>#include <queue>#include <stack>#include <list>#include <algorithm>#include <map>#include <set>#define LL long long#define Pr pair<int,int>#define fread(ch) freopen(ch,"r",stdin)#define fwrite(ch) freopen(ch,"w",stdout)using namespace std;const int INF = 0x3f3f3f3f;const int mod = 1e9+7;const double eps = 1e-8;const int maxn = 112345;int dp[999][11234];int ned[999][11234];int ans[233];int tp;void init(){ memset(dp,INF,sizeof(dp)); dp[0][0] = 0; for(int i = 1; i <= 900; ++i) { for(int j = i; j <= 10000 && j <= i*i; ++j) { for(int k = 1; k <= 9 && i-k >= 0 && j-k*k >= 0; ++k) { if(dp[i][j] > dp[i-k][j-k*k]+1) { dp[i][j] = dp[i-k][j-k*k]+1; ned[i][j] = k; } } } }}bool solve(int a,int b){ if(a > 900 || dp[a][b] > 100) return false; if(dp[a][b] == 0) return true; if(!ned[a][b]) return false; ans[tp++] = ned[a][b]; if(solve(a-ned[a][b],b-ned[a][b]*ned[a][b])) return true;}int main(){ //fread(""); //fwrite(""); init(); int t,a,b; scanf("%d",&t); while(t--) { scanf("%d%d",&a,&b); tp = 0; if(!solve(a,b)) puts("No solution"); else { for(int i = 0; i < tp; ++i) printf("%d",ans[i]); puts(""); } } return 0;}
0 0
- 【URAL 1658】1658. Sum of Digits(DP)
- URAL 1658. Sum of Digits(简单dp)
- URAL 1658 Sum of Digits (DP) #by Plato
- ural 1658. Sum of Digits
- URAL 1658. Sum of Digits
- Ural 1658 Sum of Digits
- Ural 1658 Sum of Digits
- timus 1658. Sum of Digits URAL 解题报告 DP 数字位数和……
- URAL1658 Sum of Digits(DP)
- URAL 1206 Sum of Digits of the Sum of Numbers
- Timus 1658. Sum of Digits
- ural 1014 Product of Digits
- URAL 1014 Product of Digits
- Timus Online Judge 1658 Sum of Digits
- HDU3022:Sum of Digits
- HDU3022:Sum of Digits
- B. Sum of Digits
- Sum of Digits
- myeclipse 创建和访问 servlet 项目
- python抓取动态数据 A股上市公司基本信息
- TCP三次握手和四次挥手协议
- 面试-力控华康
- 数据类型和数据表
- 【URAL 1658】1658. Sum of Digits(DP)
- TCP协议三次握手连接四次握手断开和DOS攻击
- 中大生活费估计
- 从0开始搭建:分布式服务框架-Maven多模块+Dubbo+Zookeeper++SpringMVC+mybatis自动生成
- 欧拉函数 + 约数 + 素数表 + 欧拉函数表
- 春雨医生创始人张锐突发心梗离世 享年44岁
- HDU 4770 Lights Against Dudely(2013 Asia Hangzhou Regional Contest)
- J2EE environment setup on ubuntu16.04
- 请不要重复犯我在学习Python和Linux系统上的错误