Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) D. Generating Sets 贪心

D. Generating Sets

题目连接:

http://codeforces.com/contest/722/problem/D

Description

You are given a set Y of n distinct positive integers y1, y2, …, yn.

Set X of n distinct positive integers x1, x2, …, xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X:

Take any integer xi and multiply it by two, i.e. replace xi with 2·xi.
Take any integer xi, multiply it by two and add one, i.e. replace xi with 2·xi + 1. 

Note that integers in X are not required to be distinct after each operation.

Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.

Note, that any set of integers (or its permutation) generates itself.

You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 50 000) — the number of elements in Y.

The second line contains n integers y1, …, yn (1 ≤ yi ≤ 109), that are guaranteed to be distinct.

Output

Print n integers — set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them.

Sample Input

5
1 2 3 4 5

Sample Output

4 5 2 3 1

Hint

题意

一个数x,可以变成2x,或者变成2x+1,可以变化若干次

现在给你n个不同的数Y,你需要找到n个不同的x,使得这n个不同的x经过变化之后,能够得到Y数组,你要使得最初的最大值最小。

问你应该怎么做。

题解:

贪心,每次选择最大的数,然后使得最大数变小即可,能变就变,用一个set去维护就好了。

代码

#include<bits/stdc++.h>
using namespace std;

set<int> S;
int main()
{
    int n;scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int x;scanf("%d",&x);
        S.insert(-x);
    }
    while(1)
    {
        int x=-*S.begin();
        int k = *S.begin();
        x/=2;
        while(x)
        {
            if(S.find(-x)==S.end())
            {
                S.insert(-x);
                break;
            }
            x/=2;
        }
        if(x==0)
        {
            for(auto it=S.begin();it!=S.end();it++)
                cout<<-*it<<" ";
            cout<<endl;
            return 0;
        }
        S.erase(k);
    }
    return 0;
}
    原文作者:qscqesze
    原文地址: https://www.cnblogs.com/qscqesze/p/5927554.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞