D. Generating Sets(二叉树+优先队列)

首先注意到变换是 一颗二叉树

所以我们暂时可以把初始序列抄过来

( x ) , 每次去改变最大数(记作x)的值,也就是去到这个节点的父节点

x / 2 也就是x/2

, 使 , 一旦发现这个节点没有被用过,马上使用,再把新的数放在优先队列去

? 为什么不往上继续找父节点?

, 因为只有改变最大值才是有用的,把更小的值留给后面

#include <bits/stdc++.h>
using namespace std;
const int maxn=5e5+10;
priority_queue<int>q;
map<int,int>mp;
int a[maxn],ans[maxn],b[maxn],n;
int main()
{
	cin >> n;
	for(int i=1;i<=n;i++)	cin >> a[i];
	for(int i=1;i<=n;i++)
	{
		mp[ a[i] ]=1;
		q.push( a[i] );
	}
	while( 1 )
	{
		int u=q.top(),flag=0;
		while( u )
		{
			u/=2;
			if( mp[u]==0&&u!=0 )
			{
				flag=1; mp[u]=1;
				q.pop(),q.push(u);
				break;
			}
		}
		if( flag==0 )	break;
	}
	while( !q.empty() )
	{
		cout << q.top() << " ";
		q.pop();	
	}
}

猜你喜欢

转载自blog.csdn.net/jziwjxjd/article/details/107860557