結果

問題 No.14 最小公倍数ソート
ユーザー codershifthcodershifth
提出日時 2015-07-20 01:14:43
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 4,937 ms / 5,000 ms
コード長 1,766 bytes
コンパイル時間 1,166 ms
コンパイル使用メモリ 149,276 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-22 19:36:25
合計ジャッジ時間 36,895 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 52 ms
4,376 KB
testcase_04 AC 4,937 ms
4,380 KB
testcase_05 AC 1,668 ms
4,376 KB
testcase_06 AC 1,947 ms
4,376 KB
testcase_07 AC 2,546 ms
4,376 KB
testcase_08 AC 3,334 ms
4,376 KB
testcase_09 AC 4,497 ms
4,376 KB
testcase_10 AC 4,426 ms
4,376 KB
testcase_11 AC 4,580 ms
4,380 KB
testcase_12 AC 4,721 ms
4,380 KB
testcase_13 AC 4,785 ms
4,376 KB
testcase_14 AC 4,650 ms
4,380 KB
testcase_15 AC 4,805 ms
4,376 KB
testcase_16 AC 1,781 ms
4,384 KB
testcase_17 AC 1,272 ms
4,376 KB
testcase_18 AC 566 ms
4,380 KB
testcase_19 AC 3,011 ms
4,384 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

typedef long long ll;
typedef unsigned long long ull;

#define FOR(i,a,b) for(int (i)=(a);i<(b);i++)
#define REP(i,n) FOR(i,0,n)
#define RANGE(vec) (vec).begin(),(vec).end()

using namespace std;

template<typename T>
T gcd(T a, T b) {
    if ( a < b )
        std::swap(a,b);
    if ( b == 0 )
        return a;
    return gcd(b, a%b);
}
template<typename T>
T lcm(T a, T b) {
        return a*b/gcd(a,b);
}

class LCMsort {
public:
    void solve(void) {
            int N;
            cin>>N;
            vector<int> a(N,0);
            REP(i,N)
                cin>>a[i];
            vector<int> ans;
            vector<bool> used(N,false);
            auto calc = [&](int pivot) {
                used[pivot] = true;
                int mx = (1<<30);
                int mi = -1;
                // O(N*A) pivot が更新されるにつれこのループ速度は高速化されていくはず。
                REP(i, N)
                {
                    if (used[i])
                        continue;
                    int k = lcm(a[pivot], a[i]);
                    if (k < mx || (k == mx && a[i] < a[mi]))
                    {
                        mx = k;
                        mi = i;
                    }
                }
                return mi;
            };
            // O(N^2*A)
            int pivot = 0;
            REP(i,N)
            {
                ans.push_back(a[pivot]);
                pivot = calc(pivot);
            }
            REP(i,N)
                cout<<ans[i]<<" ";
            cout<<endl;
    }
};

#if 1
int main(int argc, char *argv[])
{
        ios::sync_with_stdio(false);
        auto obj = new LCMsort();
        obj->solve();
        delete obj;
        return 0;
}
#endif
0