您的位置:首页 > 其它

Ugly Numbers--POJ 1338

2010-07-14 18:04 405 查看
1、解题思路:数论、STL。

2、注意事项:i++使用,跟踪i的值;STL的简单应用。

3、实现方法:(复杂版)

#include <iostream>
using namespace std;

int UglyNumbers[1500];

int MinNumber(int a,int b,int c)
{
int min=a;
if(min>b) min=b;
if(min>c) min=c;
return min;
}

void Init()
{
int two=0,three=0,five=0,temp;
UglyNumbers[0]=1;
for(int i=1;i<1500;i++)
{
temp=MinNumber(UglyNumbers[two]*2,UglyNumbers[three]*3,UglyNumbers[five]*5);
if(temp==UglyNumbers[two]*2)
two++;
if(temp==UglyNumbers[three]*3)
three++;
if(temp==UglyNumbers[five]*5)
five++;
UglyNumbers[i]=temp;
}
}

int seach(int x)
{
return UglyNumbers[x-1];
}

int main()
{
int n;
Init();
while(cin>>n && n)
{
cout<<seach(n)<<endl;
}
return 0;
}


4、实现方法:(STL精简版)

#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
typedef pair<unsigned long,int> node_type;

int main()
{
unsigned long result[1500];
priority_queue< node_type, vector<node_type>, greater<node_type> > Q;
Q.push( make_pair(1,2) );
for(int i=0; i<1500; i++)
{
node_type node=Q.top();
Q.pop();
switch(node.second)
{
case 2:Q.push( make_pair(node.first*2,2));
case 3:Q.push( make_pair(node.first*3,3));
case 5:Q.push( make_pair(node.first*5,5));
}
result[i]=node.first;
}
int n;    while(cin>>n && n)
{
cout<<result[n-1]<<endl;
}
return 1;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: