UVa 136 - Ugly Numbers

来源:互联网 发布:kitti数据集 百度云 编辑:程序博客网 时间:2024/05/16 05:40

仅仅几行代码就能搞定。



#include<iostream>using namespace std;int main() {    cout << "The 1500'th ugly number is 859963392." << endl;    return 0;}

百度一个数就OK了。哈哈。

好吧,上面是开玩笑,现在切入正题。


很容易就想到的办法。



#include<iostream>#define MAXN 2000using namespace std;typedef unsigned long long LL;bool ugly_num(LL x) {    if(x == 1)        return true;    if(!(x % 2))        return ugly_num(x / 2);    if(!(x % 3))        return ugly_num(x / 3);    if(!(x % 5))        return ugly_num(x / 5);    return false;}int main() {    LL i, j, uglynum[MAXN];    j = 1;    for(i = 1; j <= 1500; i++) {        if(ugly_num(i)) {            uglynum[j] = i;            j++;        }    }    cout << "The 1500'th ugly number is " << uglynum[1500] << "."     << endl;    return 0;}


如果这么写,恭喜TLE。

那么换种方法。

只能被2, 3, 5整除的才是丑数,那么从1开始乘2, 3, 5,让乘完后最小的再乘2, 3, 5。第1500次即为所求。



#include<iostream>#include<queue>#include<set>using namespace std;typedef unsigned long long LL;int k[5] = {2, 3, 5};int main() {    priority_queue<LL, vector<LL>, greater<LL> > q;    set<LL> s;    q.push(1);    s.insert(1);    for(int i = 1; i < 1500; i++) {        LL t = q.top();        q.pop();        for(int j = 0; j < 3; j++)            if(!s.count(t * k[j])) {                q.push(t * k[j]);                s.insert(t * k[j]);        }    }    cout << "The 1500'th ugly number is " << q.top() << "." << endl;    return 0;}



0 0
原创粉丝点击