Hdu3022 Sum of Digits
Sum of Digits
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 810 Accepted Submission(s): 220
Problem Description
Petka thought of a positive integer n and reported to Chapayev the sum of its digits and the sum of its squared digits. Chapayev scratched his head and said: "Well, Petka, I won't find just your number, but I can find the smallest fitting number." Can you do the same?
Input
The first line contains the number of test cases t (no more than 10000). In each of the following t lines there are numbers s1 and s2 (1 ≤ s1, s2 ≤ 10000) separated by a space. They are the sum of digits and the sum of squared digits of the number n.
Output
For each test case, output in a separate line the smallest fitting number n, or "No solution" if there is no such number or if it contains more than 100 digits.
Sample Input
4
9 81
12 9
6 10
7 9
Sample Output
9
No solution
1122
111112
Source
题目大意:求一个数字,使得这个数字每个数位上的数字和为s1,平方和为s2,输出最小的满足这个要求的数字,如果不存在,则输出No solution
分析:好题!
显然是一个dp.状态的每一维都很好确定,但它具体表示什么呢? 这就比较头疼了.令f[i][j]表示和为i,平方和为j的数的最小位数. g[i][j]表示和为i,平方和为j,最小位数为f[i][j]的最小首位数. 如果能求得这两个数组,每次输出答案的时候先输出g[s1][s2],然后s1 -= g[s1][s2],s2 -= g[s1][s2],直到s1和s2中有一个等于0.
怎么转移呢?f的转移非常简单,g的定义涉及到f,不好单独处理. 一个比较好的方法是把f和g放在一起处理. 每当f能转移的时候,就转移g.比如f[i][j]转移到f[i + k][j + k * k],那么和为i + k,j + k * k的最小位数在这个时候肯定是确定的,就是f[i + k][j + k * k],因为k是从小到大枚举的,所以g[i + k][j + k * k]也可以转移.g[j + k][j + k * k] = k. 如果f[i + k][j + k * k] == f[i][j] + 1, g的条件是满足了,但是最小首位数不一定是k,因为之前求出了f[i+k][j + k * k]是从其它的状态转移过去的,这个时候取个min.
这道题的状态表示真的挺神奇的. 状态表示的东西必须要能够得到答案和转移,并且还要满足题目的要求(最小). 考虑如何使得数最小,先是数位最少,再是首位最小.根据这两个最小就可以定义得到状态了.
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int T,s1,s2,f[910][8110],g[910][8110]; void solve() { for (int i = 1; i <= 9; i++) f[i][i * i] = 1,g[i][i * i] = i; for (int i = 1; i <= 900; i++) for (int j = 1; j <= 8100; j++) if (f[i][j]) { for (int k = 1; k <= 9; k++) { if (!f[i + k][j + k * k] || f[i + k][j + k * k] > f[i][j] + 1) { f[i + k][j + k * k] = f[i][j] + 1; g[i + k][j + k * k] = k; } else if (f[i + k][j + k * k] == f[i][j] + 1) g[i + k][j + k * k] = min(g[i + k][j + k * k],k); } } } int main() { solve(); scanf("%d",&T); while (T--) { scanf("%d%d",&s1,&s2); if (s1 > 900 || s2 > 8100 || !f[s1][s2] || f[s1][s2] > 100) printf("No solution\n"); else { while (s1 && s2) { printf("%d",g[s1][s2]); int t = g[s1][s2]; s1 -= t; s2 -= t * t; } printf("\n"); } } return 0; }