zoukankan      html  css  js  c++  java
  • Timus1014(贪心算法)

    Product of DigitsCrawling in process... Crawling failed Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

    Description

    Your task is to find the minimal positive integer number Q so that the product of digits of Q is exactly equal to N.

    Input

    The input contains the single integer number N (0 ≤ N ≤ 10 9).

    Output

    Your program should print to the output the only number Q. If such a number does not exist print −1.

    Sample Input

     
    inputoutput
    10
    
    25
    
    一般难度的贪心,问题很简单,给定一个数,求是否有一个数的各个数字的乘积等于这个数,有输出最小的,没有输出-1;
    如果简单的使用暴力枚举的话会用好久时间,我试了一下大概1000000就要三四秒,一定会超时,
    所以我们不妨重新分析题意,一个数等于另一个数各个数字乘积就是等价于,一个数等于一串数字的乘积,我们要找出最小的由这串数字组成的数;
    首先我们要保证位数最小,1是不可能出现了。0显然不可以出现,2~9我们要想让位数最小要先试大的,从9到2;
    如果找不到一个数可以整除,那么就找不到这个数作为答案,这里需要注意的是2~9的影响和0和1的影响只要把他们单拿出来就可以了;
    我觉得本题中使用的2~9的处理方法很巧妙,值得学习,还有一点就是前面的逆向思维是对以后有帮助的;
    #include<stdio.h>
    #include<math.h>
    #include<algorithm>
    using namespace std;
    int  a[123];
    
    int main()
    {
        long n;
        scanf("%d",&n);
        int t=0;
        int flag=0;
        if(n==0) {printf("10
    ");return 0;}
        if(n==1) {printf("1
    "); return 0;}
        while(n!=1)
        {
            //      cout<<"jhh"<<endl;
            int   i;
            for( i=9; i>=2; i--)
            {
                if(n%i==0)
                {
                    n/=i;
                    a[t++]=i;
                    // cout<<i<<endl;
                    break;
                }
            }
            if(i==1)
            {
                if(n<10)
                {
                    a[t++]=n;
                }
                else
                {
                    flag=1;
                }
                break;
            }
        }
        //cout<<t<<endl;
        if(flag)
        {
            printf("-1
    ");
        }
        else
        {
            sort(a,a+t);
            long long  ans=0;
            for(int i=0; i<t; i++)
            {
                ans=ans*10+a[i];
            }
            printf("%lld
    ",ans);
        }
     
  • 相关阅读:
    线程同步的三种方式(Mutex,Event,Critical Section) 沧海
    VC++多线程下内存操作的优化 沧海
    C++内存对象大会战 沧海
    技术关注:搜索引擎经验 沧海
    jira 3.13.5版 安装 配置 用户权限控制 拂晓风起
    C++ int string 转换 拂晓风起
    C++调用C链接库会出现的问题 拂晓风起
    Windows Server 2003 IIS Service Unavailable 问题解决 拂晓风起
    研究 学术 开发 的好用工具(不包括常见的) 拂晓风起
    SGMarks 问世 (Firefox扩展Gmarks的扩展版) 纯属学习 拂晓风起
  • 原文地址:https://www.cnblogs.com/VectorLin/p/5144182.html
Copyright © 2011-2022 走看看