码迷,mamicode.com
首页 > 其他好文 > 详细

Divide by three, multiply by two

时间:2018-06-24 14:10:25      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:执行   一个   8 8   nbsp   long   names   print   输出   input   

Polycarp喜欢玩数字。 他取一些整数x,写在黑板上,然后执行两种运算:
  • 将数字x除以3(x必须可以被3整除);
  • 将数字x乘以2。
你的问题是重新排序这个序列的元素,使得它可以匹配上述规则。即 每个下一个数字将是前一个数字的两倍,或者是前一个数字的三分之一。
 
保证答案的存在。

Input

输入的第一行包含整数n(2≤n≤100) - 序列中元素的数量。 输入的第二行包含n个整数a1,a2,...,an(1≤ai≤3⋅1018

Output

输出n个整数 - 重新排列后的序列,可以是原序列。
 
保证答案的存在。

Sample Input

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 
用DFS枚举可能的情况(可能性逐渐增高),直至构造出题目要求的序列
#include <iostream>
#include <cstdio>
#include <map>
#define LL long long int
using namespace std;
map<LL,int>mp;
LL a[111];
LL ans[111];
int cur,n;

int DFS(LL b)
{
    if(cur==n-1)
    {
        ans[cur++]=b;
        return 1;
    }

    if(mp[b*2])
    {
        ans[cur++]=b;
        if(DFS(b*2)) return 1;
        else cur--;
    }

    if( b%3==0 && mp[b/3])
    {
        ans[cur++]=b;
        if(DFS(b/3)) return 1;
        else return 0;
    }

    return 0;

}


int main()
{
    int i;
    cin>>n;
    for(i=0;i<n;i++)
    {
        scanf("%lld",&a[i]);
        mp[a[i]]=1;
    }
    for(i=0;i<n;i++)
    {
        cur=0;
        if(DFS(a[i]) )
            break;
    }
    for(i=0;i<n;i++)
        printf("%lld%c",ans[i],i==n-1?\n: );
    return 0;
}

 


Divide by three, multiply by two

标签:执行   一个   8 8   nbsp   long   names   print   输出   input   

原文地址:https://www.cnblogs.com/coder-tcm/p/9220331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!