POJ-1338 Ugly Numbers 递推

  题目链接:http://poj.org/problem?id=1338

  第i个数又前面的数的2,3,5的倍数决定,因此,记录2,3,5所在数位置,然后递推。

 1 //STATUS:C++_AC_0MS_172KB

 2 #include<stdio.h>

 3 #include<stdlib.h>

 4 #include<string.h>

 5 #include<math.h>

 6 #include<iostream>

 7 #include<string>

 8 #include<algorithm>

 9 #include<vector>

10 #include<queue>

11 #include<stack>

12 using namespace std;

13 #define LL __int64

14 #define pdi pair<int,int>

15 #define Max(a,b) ((a)>(b)?(a):(b))

16 #define Min(a,b) ((a)<(b)?(a):(b))

17 #define mem(a,b) memset(a,b,sizeof(a))

18 #define lson l,mid,rt<<1

19 #define rson mid+1,r,rt<<1|1

20 const int N=1510,INF=0x3f3f3f3f,MOD=1999997;

21 const double DNF=100000000000;

22 

23 int ans[N],w[3];

24 int n;

25 

26 int main()

27 {

28  //   freopen("in.txt","r",stdin);

29     int i,t[3];

30     ans[1]=w[0]=w[1]=w[2]=1;

31     for(i=2;i<=1500;i++){

32         while((t[0]=2*ans[w[0]])<=ans[i-1])w[0]++;

33         while((t[1]=3*ans[w[1]])<=ans[i-1])w[1]++;

34         while((t[2]=5*ans[w[2]])<=ans[i-1])w[2]++;

35         if(t[0]<=t[1] && t[0]<=t[2])ans[i]=t[0];

36         else if(t[1]<=t[0] && t[1]<=t[2])ans[i]=t[1];

37         else if(t[2]<=t[0] && t[2]<=t[1])ans[i]=t[2];

38     }

39     while(~scanf("%d",&n) && n)

40     {

41         printf("%d\n",ans[n]);

42     }

43     return 0;

44 }

 

你可能感兴趣的:(number)