Codeforces 977D(思维)

题面:
D. Divide by three, multiply by two
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Polycarp likes to play with numbers. He takes some integer number xx, writes it down on the board, and then performs with it n1n−1 operations of the two kinds:

  • divide the number xx by 33 (xx must be divisible by 33);
  • multiply the number xx by 22.

After each operation, Polycarp writes down the result on the board and replaces xx by the result. So there will be nn numbers on the board after all.

You are given a sequence of length nn — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.

Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.

It is guaranteed that the answer exists.

Input

The first line of the input contatins an integer number nn (2n1002≤n≤100) — the number of the elements in the sequence. The second line of the input contains nn integer numbers a1,a2,,ana1,a2,…,an (1ai310181≤ai≤3⋅1018) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Output

Print nn integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board.

It is guaranteed that the answer exists.

Examples
Input
Copy
6
4 8 6 3 12 9
Output
Copy
9 3 6 12 4 8 
Input
Copy
4
42 28 84 126
Output
Copy
126 42 84 28 
Input
Copy
2
1000000000000000000 3000000000000000000
Output
Copy
3000000000000000000 1000000000000000000 
Note

In the first example the given sequence can be rearranged in the following way: [9,3,6,12,4,8][9,3,6,12,4,8]. It can match possible Polycarp's game which started with x=9x=9.

    题目描述:给你一个被打乱的序列,每次操作,都要把这个数除以3或者乘2,使之变成下一个数,问你满足条件的原序列数。

    题目分析:这道题有很多人直接用dfs搜索答案,事实上这题没有这么麻烦。
    我们试分析,对于这个序列,因为3这个因数是要被除的,因此在整个序列中,3的个数必定是逐渐减少的。因此我们可以先统计所有数的3的个数,然后根据3的个数进行sort排序。而对于3的个数相同的时候,此时意味着不能进行除以3的操作,即只能进行*2的操作,因此,我们只需要将大的数排在后面即可。
    
#include <bits/stdc++.h>
#define maxn 105
using namespace std;
typedef long long ll;
int n;
ll a[maxn];
ll get_3(ll x){
    int cnt=0;
    while((x%3)==0) cnt++,x/=3;
    return cnt;
}
bool cmp(ll a,ll b){
    ll x=get_3(a),y=get_3(b);
    if(x==y) return a<b;
    return x>y;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+1+n,cmp);
    for(int i=1;i<=n;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39453270/article/details/80252167