poj Ugly Numbers

来源:互联网 发布:java数组按大小排序 编辑:程序博客网 时间:2024/06/11 13:23

题目:
这里写图片描述
丑数是因子只有2、3、5的数,本题要求按照从小到大的丑数数列,输入n,输出第n个丑数。
解题关键是丑数数组的构建,

AC情况:
这里写图片描述
代码:

#include<iostream>#include<algorithm>using namespace std;int s[1501] = {0,1};int main() {    int x2 = 1, x3 = 1, x5 = 1;    for (int i = 2; i < 1501; i++) {        s[i] = min(s[x2]*2,min(s[x3]*3,s[x5]*5));        if (s[i] == s[x2] * 2) x2++;        if (s[i] == s[x3] * 3) x3++;        if (s[i] == s[x5] * 5) x5++;    }    int n;    while (scanf_s("%d", &n)) {        if (n == 0) break;        printf("%d\n", s[n]);    }    return 0;}
原创粉丝点击