HDOJ3022 记忆化搜索

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
gaojie   |   We have carefully selected several similar problems for you:   3021  3023  3024  3030  3029 

分析:用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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值