【模板题】【STL】2729:Blah数集——两个指针的单调队列

2729:Blah数集:以a为基的集合Ba定义如下:(1) a是Ba的第一个元素;(2)如果x在集合Ba中,则2x+1和3x+1也都在集合Ba中;将集合Ba中元素按照升序排列,第N个元素会是多少?

思路:保持两个队列头h1、h2,分别代表产生2h1+1,3*h2+1的点。从两个头结点读取t1和t2,若t1<t2则保持t2不变,意思是下一个3*x+1还是x[h2]产生。如输入1 100,此时h1=h2=1,t1=3,t2=4,t1<t2,所以t1入队,t1++,x中为{1,3},下一次产生2h1+1的元素则为3,此时t1=7,t2=4,则4入队,t2++,x中为{1,3,4},下一次产生3*h2+1的元素为3,继续比较。。。

ps:总是超时,后来逐步排查居然是memset的原因?!求大神告知,为什么加memset会超时啊?

#include<iostream>
#include<string.h>
#define MAX 1000010
using namespace std;
int a,n,que[MAX];
void solve()
{
	int h1=1,h2=1,tail=1,t1,t2;
//	memset(que,0,sizeof(que));加这句话居然会TLE?!!?!
	que[1]=a;
	while(tail<n)
	{
		t1=(que[h1]*2)+1;t2=(que[h2]*3)+1;
		if (t1<t2)
		{
			que[++tail]=t1;
			h1++;
		}
		else if (t1>t2)
		{
			que[++tail]=t2;
			h2++;
		}
		else
		{
			que[++tail]=t1;
			h1++;h2++;
		}
	}
	cout<<que[tail]<<endl;
}
int main()
{
	while(cin>>a>>n)
		solve();
	return 0;
}

优先队列会超时:

#include<iostream>
#include<queue>
#include<string>
using namespace std;
int a,n;
struct data
{ int val;
  data(int x){ val=x;}
  bool operator < (const data &a)const
  {	  return val>a.val;  }
};
void solve()
{
	priority_queue<data> Q;
	int count=0,x;
	Q.push(data(a));
	while(count<n)
	{
		x=Q.top().val;Q.pop();
		count++;
		Q.push(data(x*2+1));
		Q.push(data(x*3+1));
	}
	cout<<x<<endl;
}
int main()
{
	while(cin>>a>>n)
		solve();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/always_ease/article/details/80765968