搜索水题

来源:互联网 发布:永久免费域名 编辑:程序博客网 时间:2024/06/07 20:54
T - dfs-easy
Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu
Submit Status

Description

Download as PDF


  Product of digits 

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


题意挺难理解滴:给你一个数n,让你找出一个最小的数,满足该数的每一位的乘积为n.

思路:每位最多有1,2,3,4,5,6,7,8,9.这9中可能。数最大为pow(10,9)。所以不用担心,搜索会超时。枚举每一位,从高位到地位,利用贪心的思想:】

#include<iostream>#include<algorithm>#include<cstdio>#include<string.h>using namespace std;int ans[20];int num[10]= {2,3,4,5,6,7,8,9};int flag;int step;void DFS(int tem,int an){    if(tem==1)    {        flag=2;        return ;    }    if(an==0&&tem%2!=0&&tem!=1)    {        flag=1;        return;    }    for(int i=an; i>=0; i--)    {        if(tem%num[i]==0)        {            ans[step++]=num[i];            DFS(tem/num[i],i);            if(flag==1||flag==2)                return ;        }        if(i==0&&tem%2!=0&&tem!=1)        {            flag=1;            return;        }    }}int main(){    int T;    int t;    scanf("%d",&T);    while(T--)    {        step=flag=0;        memset(ans,0,sizeof(ans));        scanf("%d",&t);        if(t==1)        {            printf("1\n");            continue;        }        DFS(t,7);        if(flag==1)            printf("-1");        else            for(int i=step-1; i>=0; i--)                printf("%d",ans[i]);        printf("\n");    }    return 0;}


原创粉丝点击