136 - Ugly Numbers (UVA)

题目链接如下:

Online Judge

这道题我看了刘汝佳的解法才写出来的……(暴力解法超时。另外还有一个非常简洁有趣的写法:UVA136-CSDN博客 学习一下。)代码如下:

#include 
#include 
#include 
#include 
// #define debug
const int nbr = 1500;

int main(){
    #ifdef debug
    freopen("1.txt", "w", stdout);
    #endif
    clock_t start, finish;
    start = clock();
    std::priority_queue, std::greater> q;
    long long a;
    int mul[] = {2, 3, 5};
    std::set st;
    q.push(1);
    st.insert(1);
    for(int i = 1; i <= nbr; ++i){
        a = q.top();
        q.pop();
        for(int j = 0; j < 3; ++j){
            if(!st.count(mul[j] * a)){
                st.insert(mul[j] * a);
                q.push(mul[j] * a);
            }
        }
    }
    printf("The %d'th ugly number is %lld.\n", nbr, a);
    finish = clock();
    // printf("time cost = %.2f\n", double(finish - start) / CLOCKS_PER_SEC);
    #ifdef debug
    fclose(stdout);
    #endif
    return 0;
}

你可能感兴趣的:(UVA,算法)