Openjudge2729 Blah数集(单调队列)

2729:Blah数集

总时间限制: 
3000ms
 
内存限制: 
65536kB
描述
大数学家高斯小时候偶然间发现一种有趣的自然数集合Blah,对于以a为基的集合Ba定义如下:
(1) a是集合Ba的基,且a是Ba的第一个元素;
(2)如果x在集合Ba中,则2x+1和3x+1也都在集合Ba中;
(3)没有其他元素在集合Ba中了。
现在小高斯想知道如果将集合Ba中元素按照升序排列,第N个元素会是多少?
输入
输入包括很多行,每行输入包括两个数字,集合的基a(1<=a<=50))以及所求元素序号n(1<=n<=1000000)
输出
对于每个输入,输出集合Ba的第n个元素值
样例输入
1 100
28 5437
样例输出
418
900585

如果你和我一样机智,你就直接看代码吧

#include<iostream>
using namespace std;
int a,n,head1,head2,tail,que[1000001];
void Blah()
{
    while(1)
    {
        int x=que[head1]*2+1,y=que[head2]*3+1;
        if(x>y)que[++tail]=y,head2++;//把较小的存到队列中,较大的再参与下一轮循环
        else if(x<y)que[++tail]=x,head1++;//同理
        else if(x==y)
        {
            que[++tail]=x;
            head1++;
            head2++;
        }
        if(tail>=n){
            cout<<que[n]<<endl;
            return;
        }
    }
}
int main()
{
    while(cin>>a>>n)
    {
        head1=1,head2=1,tail=1;
        que[1]=a;
        Blah();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/thmyl/p/6194719.html