Codeforces 977D 题解报告

一、题目

http://codeforces.com/contest/977/problem/D

二、分析

依题意,可以考虑一个数是3的多少次幂,可以有余数。
比如18是3的2次幂,余数为2;
9是3的2次幂,余数为0;
2是3的0次幂,余数为2。

首先要把幂从高到低的顺序排列,比如9(3的2次幂)必然排在3(3的1次幂)的前面。
对于同一次幂,要按从小到大的顺序排序,这样后面的数必然为前面的数的2倍。比如9和18都是3的2次幂。这样18就得排在9的后面。

数据结构可以使用vector

三、程序

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

typedef long long LL;

int count3(LL x)
{
    int ret = 0;
    while(x % 3 == 0)
    {
        ret++;
        x /= 3;
    }

    return ret;
}

int main()
{
    int n;
    cin >> n;

    vector<pair<int, LL>> v(n);
    for(int i = 0; i < n; i++)
    {
        cin >> v[i].second;
        v[i].first = -count3(v[i].second);
    }

    sort(v.begin(), v.end());

    for(int i = 0; i < n; i++)
    {
        printf("%I64d%c", v[i].second, " \n"[i + 1 == n]);
    }
}


TopCoder & Codeforces & AtCoder交流QQ群:648202993
更多内容请关注微信公众号
wechat_public_header.jpg

猜你喜欢

转载自blog.csdn.net/haishu_zheng/article/details/80240262
今日推荐