Set Definition(两个一次函数)

来源:互联网 发布:软件新城二期 编辑:程序博客网 时间:2024/05/22 03:45

                                                                                                                      Set Definition
Time Limit: 1000MS
Memory Limit: 65536KTotal Submissions: 8784
Accepted: 4036

Description

Set S is defined as follows:
(1) 1 is in S;
(2) If x is in S, then 2x + 1 and 3x + 1 are also in S;
(3) No other element belongs to S.

Find the N-th element of set S, if we sort the elements in S by increasing order.

Input

Input will contain several test cases; each contains a single positive integer N (1 <= N <= 10000000), which has been described above.

Output

For each test case, output the corresponding element in S.

Sample Input

100254

Sample Output

4181461

Source

POJ Monthly--2005.08.28,Static


题解:N 的范围是10000000,显然预处理出所有数,然后查表输出。打表时注意数字之间的大小关系,2*x+1和3*x+1显然都是线性递增关系,那么从小到大查询数的过程也是线性的。稍稍注意2*X1+1与3*X2+1相等的情况。

做题时应该多注意题目所给的内存限制和时间限制。由于此题给定内存较大,所以10^7的数组大胆开。


#include<cstdio>#include<cstring>#include<iostream>using namespace std;#define maxn 10000005int num[maxn];int main(){    num[1]=1;    int n,cnt=1,head1=1,head2=1;//head1为从前向后扫描2*x+1的情况,head2为从前向后扫描3*x+1的情况    while(true)    {        if(cnt==10000000)break;        int n1=2*num[head1]+1,n2=3*num[head2]+1;        if(n1<n2)num[++cnt]=n1,++head1;        else num[++cnt]=n2,++head2;//num[cnt]为当前2种情况的较小值        if(n1==n2)head1++;//两种情况算出的数字相等时,都要进行+1操作。    }    while(~scanf("%d",&n))printf("%d\n",num[n]);    return 0;}