CF 977D stl vector,pair

题目

Polycarp likes to play with numbers. He takes some integer number
divide the number
multiply the number

After each operation, Polycarp writes down the result on the board and replaces
You are given a sequence of length n

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 n
Output

Print

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 

Note

In the first example the given sequence can be rearranged in the following way: [9,3,6,12,4,8]

大意:
所有数排序,使得这个数的下一个数是它的2倍或者1/3

输出正确的顺序

思路:

利用pair的特性,先排first,后排second

题目给出,答案一定存在。
假若这个序列是由一个数不断除以3得到的

81  27  9   3

那么排在最前面的数 能被3整除的次数是最大的,后面的数依次递减

                81  27  9   3
被3整除的次数:   4   3   2  1 

这样我们就有了一个初步的思路,所有的数按 能被3整除的次数大小 来排列

接着我们再看,如果这个数乘2了怎么办???

假若 27 乘2,那么我们就得到了 54
54 能被3整除的次数 =3 , 与27相等!!!

不断举例,我们会发现一个数乘以2之后,不会改变他能被3整除的次数
所以相等的次数。。。大的那个肯定就是小的那个数的2倍啦
(为什么呢,不告 诉你 ,题目说啦,答案一定存在)

这样我们就找到了解题方法:
1.先算出所有数 能被3整除的次数,
次数存到pair中的前一个值(first)
把这个数存到pair的后一个值(second)

2.要知道,pair默认排序方式是从小到大排

扫描二维码关注公众号,回复: 9483925 查看本文章

我们需要的是 次数大的在前面,那么次数加个负号,就可以做到啦
你可真是个小机灵鬼(~ ̄▽ ̄)~

下一个数可以是这个数的两倍,second从小到大排正好符合了这个要求。

代码

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll num(ll x)
{
    ll sum=0;
    while(x!=0 && x%3==0)
    {
        sum++;
        x=x/3;
    }
    return sum;
}

vector<pair<ll,ll> > f;

int main(){
  int n;
  cin>>n;
  f.resize(n);
  for(ll i=0; i<n; i++)
  {
      cin>>f[i].second;
      f[i].first=-num(f[i].second);
  }

  sort(f.begin(), f.end());
  vector<pair<ll,ll> >::iterator it;
  for(it=f.begin();it!=f.end();it++)
  {
      cout<<(*it).second;
      n--;
      if(n!=0)cout<<" ";
  }
 
  return 0;
}

知识点

      cin>>f[i].second;
      f[i].first=-num(f[i].second);
      ///单独输入
   若输入一对可用f.push_back(make_pair(10,20));
 sort(f.begin(), f.end());
 如果前面不加负号,那么可以定义cmp排序方式
 bool cmp1(pair<int,int>a,pair<int,int>b){return a.first < b.first;}
输出一:
 vector<pair<ll,ll> >::iterator it;
  for(it=f.begin();it!=f.end();it++)
  {
      cout<<(*it).second;
      n--;
      if(n!=0)cout<<" ";
  }
  
输出二:
 for(ll i=0; i<n; i++)
    printf("%lld%c", f[i].second, " \n"[i + 1 == n]);
    
若i+1==n不成立,等于0  那么就输出 " \n"的第0个  即“ ”
若成立,等于1   那么输出" \n"的第1个  即“\n”
发布了46 篇原创文章 · 获赞 0 · 访问量 1137

猜你喜欢

转载自blog.csdn.net/weixin_45719073/article/details/104461756