結果

問題 No.14 最小公倍数ソート
ユーザー square1001square1001
提出日時 2022-02-17 13:21:23
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 5 ms / 5,000 ms
コード長 1,435 bytes
コンパイル時間 571 ms
コンパイル使用メモリ 68,108 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-09-11 17:38:59
合計ジャッジ時間 1,512 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 2 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 3 ms
4,380 KB
testcase_04 AC 5 ms
4,376 KB
testcase_05 AC 3 ms
4,376 KB
testcase_06 AC 4 ms
4,376 KB
testcase_07 AC 4 ms
4,380 KB
testcase_08 AC 4 ms
4,380 KB
testcase_09 AC 5 ms
4,380 KB
testcase_10 AC 5 ms
4,380 KB
testcase_11 AC 5 ms
4,384 KB
testcase_12 AC 5 ms
4,380 KB
testcase_13 AC 5 ms
4,380 KB
testcase_14 AC 5 ms
4,376 KB
testcase_15 AC 5 ms
4,376 KB
testcase_16 AC 4 ms
4,376 KB
testcase_17 AC 4 ms
4,376 KB
testcase_18 AC 3 ms
4,376 KB
testcase_19 AC 5 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
using namespace std;

int N, LIMIT, A[10240], cnt[10240], divpos[10240], divsep[10240], divs[94208]; bool canuse[10240];

int main() {
	// step #1. read input
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> A[i];
	}
	
	// step #2. pre-calculation
	LIMIT = *max_element(A, A + N);
	for (int i = 1; i < N; i++) {
		cnt[A[i]]++;
	}
	for (int i = 1; i <= LIMIT; i++) {
		for (int j = i; j <= LIMIT; j += i) {
			divsep[j + 2]++;
		}
	}
	for (int i = 1; i <= LIMIT; i++) {
		divsep[i + 2] += divsep[i + 1];
	}
	for (int i = 1; i <= LIMIT; i++) {
		for (int j = i; j <= LIMIT; j += i) {
			divs[divsep[j + 1]++] = i;
		}
	}
	
	// step #3. calculate and output the answer from the leftmost element
	int preval = A[0];
	for (int i = 1; i < N; i++) {
		canuse[A[i]] = true;
	}
	cout << A[0];
	while (true) {
		int optval = -1, optlcm = (1 << 30);
		for (int i = divsep[preval]; i < divsep[preval + 1]; i++) {
			int x = divs[i];
			while (divpos[x] <= LIMIT && !canuse[divpos[x]]) {
				divpos[x] += x;
			}
			if (divpos[x] <= LIMIT) {
				int curlcm = preval / x * divpos[x];
				if (optlcm > curlcm) {
					optlcm = curlcm;
					optval = divpos[x];
				}
			}
		}
		if (optval == -1) {
			break;
		}
		for (int i = 0; i < cnt[optval]; i++) {
			cout << ' ' << optval;
		}
		canuse[optval] = false;
		preval = optval;
	}
	cout << endl;
	
	return 0;
}
0