Ugly Numbers--POJ 1338

1、解题思路:数论、STL。

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

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

  
    
1 #include < iostream >
2 using namespace std;
3
4 int UglyNumbers[ 1500 ];
5
6 int MinNumber( int a, int b, int c)
7 {
8 int min = a;
9 if (min > b) min = b;
10 if (min > c) min = c;
11 return min;
12 }
13
14 void Init()
15 {
16 int two = 0 ,three = 0 ,five = 0 ,temp;
17 UglyNumbers[ 0 ] = 1 ;
18 for ( int i = 1 ;i < 1500 ;i ++ )
19 {
20 temp = MinNumber(UglyNumbers[two] * 2 ,UglyNumbers[three] * 3 ,UglyNumbers[five] * 5 );
21 if (temp == UglyNumbers[two] * 2 )
22 two ++ ;
23 if (temp == UglyNumbers[three] * 3 )
24 three ++ ;
25 if (temp == UglyNumbers[five] * 5 )
26 five ++ ;
27 UglyNumbers[i] = temp;
28 }
29 }
30
31 int seach( int x)
32 {
33 return UglyNumbers[x - 1 ];
34 }
35
36 int main()
37 {
38 int n;
39 Init();
40 while (cin >> n && n)
41 {
42 cout << seach(n) << endl;
43 }
44 return 0 ;
45 }
46

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

  
    
1 #include < algorithm >
2 #include < iostream >
3 #include < queue >
4   using namespace std;
5 typedef pair < unsigned long , int > node_type;
6
7 int main()
8 {
9 unsigned long result[ 1500 ];
10 priority_queue < node_type, vector < node_type > , greater < node_type > > Q;
11 Q.push( make_pair( 1 , 2 ) );
12 for ( int i = 0 ; i < 1500 ; i ++ )
13 {
14 node_type node = Q.top();
15 Q.pop();
16 switch (node.second)
17 {
18 case 2 :Q.push( make_pair(node.first * 2 , 2 ));
19 case 3 :Q.push( make_pair(node.first * 3 , 3 ));
20 case 5 :Q.push( make_pair(node.first * 5 , 5 ));
21 }
22 result[i] = node.first;
23 }
24 int n; while (cin >> n && n)
25 {
26 cout << result[n - 1 ] << endl;
27 }
28 return 1 ;}

 

 

你可能感兴趣的:(number)