题目描述:
Polycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n−1 operations of the two kinds:
divide the number x by 3 (x must be divisible by 3);
multiply the number x by 2.
After each operation, Polycarp writes down the result on the board and replaces x by the result. So there will be n numbers on the board after all.
You are given a sequence of length n — 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.
输入描述:
The first line of the input contatins an integer number n (2≤n≤100) — the number of the elements in the sequence. The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤3⋅1018) — rearranged (reordered) sequence that Polycarp can wrote down on the board.
输出描述:
Print n 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.
输入:
6
4 8 6 3 12 9
4
42 28 84 126
2
1000000000000000000 3000000000000000000
输出:
9 3 6 12 4 8
126 42 84 28
3000000000000000000 1000000000000000000
题意:
黑板上写下一个数字 x ,然后进行 n-1 次以下两种操作:
x 除以3 (必须能整除才能进行,即 x mod 3=0)
x 乘以2
找出一种可能的序列
题解:
直接爆搜
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<map>
using namespace std;
const int maxn = 100 + 5;
typedef long long ll;
ll b[maxn],a[maxn];
int n,t;
map<ll,int>mp;
bool flag;
void dfs(ll x){
if(t == n - 1){
flag = true;
for(int i = 0; i < t; i ++){
printf("%lld ",b[i]);
}
printf("%lld\n",b[t]);
}
if(x % (ll)3 == 0 && mp[x / (ll)3] == 1){
t ++;
b[t] = x / (ll)3;
dfs(x / (ll)3);
}
if(mp[x * (ll)2] == 1){
t ++;
b[t] = x * (ll)2;
dfs(x * (ll)2);
}
}
int main(){
while(scanf("%d",&n)!=EOF){
mp.clear();
for(int i = 0; i < n; i ++){
scanf("%lld",&a[i]);
mp[a[i]] = 1;
}
//t = 0;
flag = false;
for(int i = 0; i < n; i ++){
t = 0;
b[0] = a[i];
dfs(a[i]);
if(flag) break;
}
}
return 0;
}