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);
        }
     
  • 相关阅读:
    SQL Server Profiler使用方法
    RichTextBox控件-主要用于输入输出编辑文本信息
    ComboBox
    另一个 SqlParameterCollection 中已包含 SqlParameter
    GUID全局唯一标识符
    MDI-多文档窗体
    【转】classpath和环境变量设置
    接口、抽象类都要单建(好习惯)
    Java基础部分回顾(为自己)
    Java基础——ArrayList与LinkedList(二)
  • 原文地址:https://www.cnblogs.com/VectorLin/p/5144182.html
Copyright © 2011-2022 走看看