NOI 3.4 队列 2729:Blah数集

题目来源:http://noi.openjudge.cn/ch0304/2729/

2729:Blah数集

总时间限制3000ms     内存限制65536kB

描述

大数学家高斯小时候偶然间发现一种有趣的自然数集合Blah,对于以a为基的集合Ba定义如下:
(1) a
是集合Ba的基,且aBa的第一个元素;
(2)
如果x在集合Ba中,则2x+13x+1也都在集合Ba中;
(3)
没有其他元素在集合Ba中了。
现在小高斯想知道如果将集合Ba中元素按照升序排列,第N个元素会是多少?

输入

输入包括很多行,每行输入包括两个数字,集合的基a(1<=a<=50))以及所求元素序号n(1<=n<=1000000)

输出

对于每个输入,输出集合Ba的第n个元素值

样例输入

1 100
28 5437

样例输出

418
900585

-----------------------------------------------------

思路

设置两个指针h1,h2, 分别指向队列末尾的两个数,以q[h1],q[h2]为基数有x1=2*q[h1]+1, x2=3*q[h2]+1, x1,x2中较小者入队,同时相应指针+1,另一个指针不动,即较大者留待下一轮比较入队。如果x1==x2, 则两个指针都+1,否则会出现重复入队的情况。

还有就是关于队列的数据类型问题,要不要用long long int呢?答案是不用的。因为集合中的每个元素都会派生出两个元素,形成一个完全二叉树的结构,完全二叉树的结点个数(本题的n)与层数(c)是n=2^c-1的关系,而按照题目中的构造方法,二叉树中的最大元素max_element与层数c近似是max_element = a * 3^(c-1)的关系,所以max_element与n是线性关系,n在int的范围内,所以max_element也在int范围内。

-----------------------------------------------------

代码 

#include<iostream>
#include<fstream>
using namespace std;

const int NMAX = 1000005;
int q[NMAX] = {};

int main()
{
#ifndef ONLINE_JUDGE
	ifstream fin ("0304_2729.txt");
	int n,h1,h2,tail,a,x1,x2;
	while (fin >> a >> n)
	{
		h1 = 0;
		h2 = 0;
		tail = 0;
		q[0] = a;
		while (tail < n)
		{
			x1 = q[h1]*2+1;
			x2 = q[h2]*3+1;
			if (x1<x2)
			{
				q[++tail] = x1;
				h1++;
			}
			else if (x1>x2)
			{
				q[++tail] = x2;
				h2++;
			}
			else
			{
				q[++tail] = x1;
				h1++;
				h2++;
			}
		}
		cout << q[n-1] << endl;
	}
	fin.close();
#endif
#ifdef ONLINE_JUDGE
	int n,h1,h2,tail,a,x1,x2;
	while (cin >> a >> n)
	{
		h1 = 0;
		h2 = 0;
		tail = 0;
		q[0] = a;
		while (tail < n)
		{
			x1 = q[h1]*2+1;
			x2 = q[h2]*3+1;
			if (x1<x2)
			{
				q[++tail] = x1;
				h1++;
			}
			else if (x1>x2)
			{
				q[++tail] = x2;
				h2++;
			}
			else
			{
				q[++tail] = x1;
				h1++;
				h2++;
			}
		}
		cout << q[n-1] << endl;
	}
#endif
}


猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/80702088
3.4