zoukankan      html  css  js  c++  java
  • poj 1338 Ugly Numbers 枚举素因子幂

      依据题目要求,则任意满足要求的N有如下关系

           ,  其中 ( x, y, z ) 为自然数

      那么我们需要前1500个.

      则可以通过枚举 x, y, z 来得出.

      问题就转换成了如何枚举 x, y, z 使其不重复,且按照从小到大的顺序得出.

      假定,我们已经求得了第 Ai 个 Ugly Number

      那么, Ai*2,Ai*3,Ai*5 也必定是 Ugly Number, 这也确实是这样.但是我们想要知道的是其顺序大小关系.

      第i个Ugly Number 为Ai, i+1个Ugly Number该如何求呢.

      它必定是前面已求得的一个数 Aj, 通过 *2, *3, *5 ,增加一个素因子(2,3,5)得到.

      如果我们保存上一次分别通过 *2, *3, *5 得到的 Ax, Ay, Az 我们就可以知道 i+1个 Ugly Number..

      则当前 Ai+1 = Min{ Ax*2, Ay*3, Az*5 }

      注意更新 Ax, Ay, Az .

    解题代码:

    #include<stdio.h>
    #include<string.h>
    typedef long long LL;
    LL res[1520];
    #define MIN(a,b) (a)<(b)?(a):(b)
    void init()
    {
        int idx = 1;
        res[idx++] = 1;
        int a2 = 1, a3 = 1, a5 = 1;
        while( idx <= 1500 )    
        {
            LL val = MIN( res[a2]*2, MIN( res[a3]*3, res[a5]*5 ) );
            if(    val == res[a2]*2 )    a2++;
            if( val == res[a3]*3 )    a3++;
            if( val == res[a5]*5 )    a5++;
            res[idx++] = val;
        }
    }
    int main()
    {
        init();
        int n;
        while( scanf("%d",&n), n )
            printf("%lld\n", res[n] );
        return 0;
    }
  • 相关阅读:
    BIOS/MBR UEFI/GPT关系与区别-资料整理
    raid 简单了解
    MBR主引导记录
    linux 安装vscode
    chrome 获得点击按钮时的事件
    python计算纪念日相关
    python error: curl: (1) Protocol "'https" not supported or disabled in libcurl
    linux go with vscode
    postman 进阶技巧
    mysql常用时间函数与类型转换
  • 原文地址:https://www.cnblogs.com/yefeng1627/p/2856883.html
Copyright © 2011-2022 走看看