https://vjudge.net/contest/240386#problem/G
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘<number>’ replaced by the number computed. Sample Output The 1500'th ugly number is <number>.
一步一步改进的代码
第一次(WA)
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <vector>
#define maxn 1e5+10
using namespace std;
set<long int> s;
vector<int> v;
int main()
{
long int i,c=0;
set<long int>::iterator it1;
s.insert(1);
for(i=1;;++i)
{
if(s.size()>=1500) break;
it1=s.find(i);
if(it1!=s.end())
{
s.insert(i*2);
s.insert(i*3);
s.insert(i*5);
}
}
set<long int>::iterator it;
it=s.begin();
for(i=1;i<=1499;++i)
it++;
printf("The 1500'th ugly number is %d.\n",(*it));
return 0;
}
改进后:(TL)
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
set<long int> s;
long int min(long int a,long int b,long int c)
{
long int min=a;
if(min>b) min=b;
if(min>c) min=c;
return min;
}
int main()
{
long int i1,i2,i3,c;
i1=i2=i3=1;
s.insert(1);
while(1)
{
if(s.size()==1500) break;
if(!s.count(i1)) {i1++;continue;}
if(!s.count(i2)) {i2++;continue;}
if(!s.count(i3)) {i3++;continue;}
c=min(i1*2,i2*3,i3*5);
if(c==i1*2) i1++;
if(c==i2*3) i2++;
if(c==i3*5) i3++;
s.insert(c);
}
set<long int>::iterator it;
it=s.end();
it--;
printf("The 1500'th ugly number is %d.\n",(*it));
return 0;
}
再次改进(AC):
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
set<long int> s;
long int min(long int a,long int b,long int c)
{
long int min=a;
if(min>b) min=b;
if(min>c) min=c;
return min;
}
int main()
{
long int i1,i2,i3,c;
i1=i2=i3=1;
s.insert(1);
set<long int>::iterator it1,it2,it3;
it1=s.begin();
it2=s.begin();
it3=s.begin();
while(1)
{
if(s.size()==1500) break;
c=min(i1*2,i2*3,i3*5);
if(c==i1*2) i1=*(++it1);
if(c==i2*3) i2=*(++it2);
if(c==i3*5) i3=*(++it3);
s.insert(c);
}
set<long int>::iterator it;
it=s.end();
it--;
printf("The 1500'th ugly number is %d.\n",(*it));
return 0;
}
路漫漫呀!本质还是思维没考虑全