UVa 993 - Product of digits

 【链接】

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=113&page=show_problem&problem=934


【原题】

For a given non-negative integer number N , find the minimal natural Q such that the product of all digits of Q is equal N .

Input 

The first line of input contains one positive integer number, which is the number of data sets. Each subsequent line contains one data set which consists of one non-negative integer number N (0$ \le$N$ \le$109) .

Output 

For each data set, write one line containing the corresponding natural number Q or `-1' if Q does not exist.

Sample Input 

3 
1 
10 
123456789

Sample Output 

1 
25 
-1


【题目大意】

product: 乘积

输入一个非负数N,找到一个最小的自然数Q,使得Q上的每一位数相乘的结果等于N


【分析与总结】

容易想到的是用搜索来做。在搜索之前需要做些剪枝的处理:找到所有能被N整除的数(N的约数),只有这些数才能构成最终答案。

然后就是按照答案Q的长度进行迭代加深搜索,Q的长度从1~10。 

有一点需要注意的地方:最高位数不能是1! 



【代码】

/*
 * UVa:  993 - Product of digits
 * Result: Accept
 * Time: 0.008s
 * Author: D_Double
 */
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
bool vis[10];
int fact[10], nIndex, cur, N;
int number[10];
bool flag;

void dfs(int cur, int sum, int max){
    if(cur >= max){
        if(sum==N) flag=true;
        return ;
    }
    if(sum > N) return;
    if(flag) return;
    for(int i=0; i<nIndex; ++i){
        if(cur==0&&i==0&&fact[i]==1) continue;// 注意,最高位不能是1,因为乘1没意义而且使结果大10倍
        number[cur] = fact[i];
        dfs(cur+1, sum*number[cur], max);
        if(flag) return;
    }
}


int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&N);
        if(N<10) {
            printf("%d\n", N);
            continue;
        }
        memset(vis, false, sizeof(vis));
        nIndex = 0;
        for(int i=1; i<=9; ++i) if(N%i==0)
            fact[nIndex++] = i;

        flag = false;
        int i;
        for(i=2; i<=10; ++i){
            dfs(0, 1, i);
            if(flag) break;
        }
        if(flag) {
            for(int j=0; j<i; ++j) printf("%d", number[j]);
            printf("\n");
        }
        else 
            printf("-1\n");
    }
    return 0;
}


 

——  生命的意义,在于赋予它意义。

          
     原创 http://blog.csdn.net/shuangde800 , By   D_Double  (转载请标明)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值