题目链接如下:
这道题我看了刘汝佳的解法才写出来的……(暴力解法超时。另外还有一个非常简洁有趣的写法:UVA136-CSDN博客 学习一下。)代码如下:
#include <cstdio>
#include <time.h>
#include <set>
#include <queue>
// #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<long long, std::vector<long long>, std::greater<long long>> q;
long long a;
int mul[] = {2, 3, 5};
std::set<long long> 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;
}