维护三个数组q1,q2,q3;
取q2、q3队首元素的较小者k,加入q1,相应队列的队首位置后移,
2*k+1、3*k+1分别加入q2、q3;
直到q1中的元素个数达到n个。
实际上,q2、q3中的元素都来自于q1,只要维护two、three两个位置,表示q2中的下一个数由q1[two]*2+1得到,q3中的下一个数由q1[three]*3+1得到,这样就不需要q2、q3这两个数组了。
特殊情况的处理:q2、q3的队首元素相同。
代码:
#include<iostream>
#define M 1000000
using namespace std;
int q[M];
void work(int a,int n)
{
q[1]=a;
int two=1,three=1,near=2;
while(near<=n)
{
long long t1=2*q[two]+1,t2=3*q[three]+1;
long long t=min(t1,t2);
if(t1<t2)
two++;
else
three++;
if(t!=q[near-1])
q[near++]=t;
}
cout<<q[n]<<endl;
}
int main()
{
int a,n;
while(cin>>a>>n)
work(a,n);
return 0;
}