【Codeforces - 977D】Divide by three, multiply by two(思维构造)
題干:
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.
Input
The 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?nninteger numbers?a1,a2,…,ana1,a2,…,an?(1≤ai≤3?10181≤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
6 4 8 6 3 12 9Output
9 3 6 12 4 8Input
4 42 28 84 126Output
126 42 84 28Input
2 1000000000000000000 3000000000000000000Output
3000000000000000000 1000000000000000000Note
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.
題目大意:
給定n個數,找到他的一個重新排列,使得第一個數開始通過除3或乘2,可以得到這個序列。(n<=100. a[i]<=3e18)
解題報告:
設cnt3是一個數中3的因子個數。
因為只有/3的操作,所以排完的整個數組中的數cnt3一定是單調不遞增的,
而相同的cnt3中的數,關系一定是*2的關系,那么一定是單調遞增的排序。
所以先按cnt3降序排序,cnt3相同的升序排序,直接輸出即可。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n; struct Node {ll a,b;bool operator < (const Node & o) const {if(b != o.b) return b > o.b;else return a < o.a;} } R[MAX]; int main() {cin>>n;for(int i = 1; i<=n; i++) {scanf("%lld",&R[i].a);ll x = R[i].a;while(x%3 == 0) x/=3,R[i].b++;}sort(R+1,R+n+1);for(int i = 1; i<=n; i++) printf("%lld ",R[i].a);return 0 ; }?
總結
以上是生活随笔為你收集整理的【Codeforces - 977D】Divide by three, multiply by two(思维构造)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 零百加速3秒级!华为徐直军:第一次见阿维
- 下一篇: 马斯克:美国或跟日本一样 不解决生育问题