結果

問題 No.14 最小公倍数ソート
ユーザー codershifthcodershifth
提出日時 2015-07-20 09:41:23
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 4,545 ms / 5,000 ms
コード長 1,819 bytes
コンパイル時間 1,474 ms
コンパイル使用メモリ 145,876 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-22 20:32:59
合計ジャッジ時間 52,170 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 47 ms
4,376 KB
testcase_04 AC 4,545 ms
4,376 KB
testcase_05 AC 1,528 ms
4,376 KB
testcase_06 AC 1,788 ms
4,376 KB
testcase_07 AC 2,328 ms
4,376 KB
testcase_08 AC 3,071 ms
4,376 KB
testcase_09 AC 4,160 ms
4,376 KB
testcase_10 AC 4,091 ms
4,376 KB
testcase_11 AC 4,228 ms
4,380 KB
testcase_12 AC 4,355 ms
4,380 KB
testcase_13 AC 4,401 ms
4,384 KB
testcase_14 AC 4,278 ms
4,380 KB
testcase_15 AC 4,440 ms
4,380 KB
testcase_16 AC 1,642 ms
4,376 KB
testcase_17 AC 1,179 ms
4,380 KB
testcase_18 AC 523 ms
4,376 KB
testcase_19 AC 2,771 ms
4,376 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>
inline 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];

            // sort を進めるにつれソート対象列が短くなるので、実際にソートするのでなく、lcm が最も小さい
            // ものを取り出していくだけでよい。
            // O(N^2*A)
            REP(pivot,N)
            {
                cout<<a[pivot]<<" ";
                int mx = (1<<30);
                int mi = -1;
                // O(N*A) pivot が更新されるにつれこのループ速度は高速化されていくはず。
                FOR(i, pivot+1, N)
                {
                    int k = lcm(a[pivot], a[i]);
                    if (k < mx || (k == mx && a[i] < a[mi]))
                    {
                        mx = k;
                        mi = i;
                    }
                }
                if (mi < 0)
                    break;
                // pivot を入れ替えることで FOR(i, pivot+1, N) のループ回数を減らせる
                swap(a[pivot+1], a[mi]);
            }
            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