您的位置:首页 > 其它

dp Sum of Digits

2012-04-03 17:03 295 查看

Sum of Digits

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 181 Accepted Submission(s): 53


[align=left]Problem Description[/align]
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?

[align=left]Input[/align]
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.

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

4
9
81
12
9
6
10
7
9

[align=left]Sample Output[/align]

9
No solution
1122
111112

View Code

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
char dp[901][8101];//length
char d[901][8101];//last digit
int main() {
for (int i = 1;i <= 9;i++) {
dp[i][i * i] = 1;
d[i][i * i] = i;
}
for (int i = 1;i <= 900;i++)
{
for (int j = i;j <= 8100;j++)
{
for (int k = 1;i>k&&k <= 9&&j>=k*k;k++)
{
/* if(dp[i-k][j-k*k]!=0&&(dp[i][j]==0||dp[i][j]>dp[i-k][j-k*k]*10+k))
{
dp[i][j]=dp[i-k][i-k*k]*10+k;
}*/
if (i < k || j < k * k) break;
if (dp[i - k][j - k * k] == 0 || dp[i - k][j - k * k] == 100) continue;
if (dp[i][j] == 0 || dp[i - k][j - k * k] + 1  < dp[i][j]) {
dp[i][j] = dp[i - k][j - k * k] + 1;
d[i][j] = k;
}
}
}
}
int n,a,b;
scanf("%d",&n);
while (n--) {
scanf("%d%d",&a,&b);
if (a > 900 || b > 8100 || dp[a][b] == 0) {
puts("No solution");
continue;
}
while (dp[a][b])
{
int digit = d[a][b];
printf("%d",digit);
a -= digit;
b -= digit * digit;
}
//printf("%d\n",dp[a][b]);
puts("");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: