Sum of Digits
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 783 Accepted Submission(s): 211
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
Recommend
分析:用dp[i][j]表示和为i,平方和为j的最小的数。假设每一位都是9,那么i=9*100=900, j = 9*9*100=8100.
数组开[900][8100]就足够了,然后记忆化搜索进行查找。
代码如下:
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 900+5;
const int maxm = 8100+5;
int dp[maxn][maxm],num[maxn][maxm];
int n,m;
int DP(int n, int m){
if (dp[n][m]!=-1) return dp[n][m];
if (n==0 && m==0) return dp[n][m]=0;
if (n==0 || m==0 || n>m) return dp[n][m]=105;
dp[n][m] = 105;
int tmp;
for (int i=1; i<=9; i++) {
if (n-i>=0 && m-i*i>=0) {
tmp = DP(n-i,m-i*i);
if (tmp+1<dp[n][m]) {
dp[n][m] = tmp+1;
num[n][m] = i;
}
}
}
return dp[n][m];
}
void Print(int i, int n, int m){
printf("%d",num[n][m]);
if (i>1) Print(i-1,n-num[n][m],m-num[n][m]*num[n][m]);
}
int main(){
int T;
scanf("%d",&T);
memset(num,-1,sizeof(num));
memset(dp,-1,sizeof(dp));
while (T--){
scanf("%d %d",&n,&m);
int nm = 105;
if (n<=m && n<=900 && m<=8100) nm = DP(n,m);
if (nm>100) printf("No solution\n");
else {
Print(nm,n,m);
printf("\n");
}
}
return 0;
}