Polycarp likes to play with numbers. He takes some integer number xx
, writes it down on the board, and then performs with it n−1n−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.InputThe first line of the input contatins an integer number nn
(2≤n≤1002≤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
(1≤ai≤3⋅10181≤ai≤3⋅1018
) — rearranged (reordered) sequence that Polycarp can wrote down on the board.OutputPrint 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 6
4 8 6 3 12 9
Output 9 3 6 12 4 8
Input 4
42 28 84 126
Output 126 42 84 28
Input 2
1000000000000000000 3000000000000000000
Output 3000000000000000000 1000000000000000000
NoteIn 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
题目不难,但由于被C题卡了导致结束后十几分钟才改出来
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <iomanip>
#define INF 0x3f3f3f3f
#define m 2008
long long a[110];
int b[110];
int c[110];
using namespace std;
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
sort(a+1,a+n+1);
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
for(int i=1;i<n;i++)
for(int j=i+1;j<=n;j++)
if(a[j]==a[i]*2||a[j]==a[i]*3)
{
b[i]++;
b[j]++;
}
long long first=-1;
for(int i=1;i<=n;i++)
{
if(first!=-1) break;
if(b[i]==1)
for(int j=1;j<=n;j++)
if(a[j]*3==a[i]||a[j]==a[i]*2)
{
first=a[i];
c[i]=1;
break;
}
}
cout<<first<<" ";
long long now=first;
for(int k=1;k<n;k++)
{
for(int i=1;i<=n;i++)
if((now==a[i]*3&&c[i]==0)||(now*2==a[i]&&c[i]==0))
{
cout<<a[i]<<" ";
now=a[i];
c[i]=1;
continue;
}
}
return 0;
}
具体思路如图,以第一个样例为例(上方连续为3倍,下方为2倍)
不难看出,只有一条线连接的数必定是第一个数或最后一个数,只要判断这个数是否有成三倍或二倍的关系即可,不可能存在两个数都可以作为起点的情况