結果

問題 No.14 最小公倍数ソート
ユーザー FF256grhyFF256grhy
提出日時 2015-06-04 18:15:36
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 993 ms / 5,000 ms
コード長 1,541 bytes
コンパイル時間 814 ms
コンパイル使用メモリ 26,844 KB
実行使用メモリ 5,616 KB
最終ジャッジ日時 2023-09-20 19:09:46
合計ジャッジ時間 13,513 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,576 KB
testcase_01 AC 4 ms
5,564 KB
testcase_02 AC 4 ms
5,500 KB
testcase_03 AC 51 ms
5,612 KB
testcase_04 AC 993 ms
5,612 KB
testcase_05 AC 362 ms
5,612 KB
testcase_06 AC 446 ms
5,548 KB
testcase_07 AC 583 ms
5,616 KB
testcase_08 AC 713 ms
5,552 KB
testcase_09 AC 952 ms
5,596 KB
testcase_10 AC 941 ms
5,596 KB
testcase_11 AC 962 ms
5,596 KB
testcase_12 AC 956 ms
5,560 KB
testcase_13 AC 954 ms
5,568 KB
testcase_14 AC 950 ms
5,612 KB
testcase_15 AC 959 ms
5,556 KB
testcase_16 AC 620 ms
5,608 KB
testcase_17 AC 511 ms
5,484 KB
testcase_18 AC 296 ms
5,556 KB
testcase_19 AC 816 ms
5,580 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <stdio.h>

#define MAX 10000

int gcd(int, int);
int lcm(int, int);

int n, pre, bucket[MAX + 1];
int div_num[MAX + 1], div_table[MAX + 1][64]; // 約数は最大でも64個(7560, 9240のとき)

int main(void) {
	scanf("%d %d", &n, &pre);
	printf("%d ", pre);
	
	int i, j;
	for(i = 1; i < n; i++) { // 最初の1個以外は順番関係ない
		int temp;
		scanf("%d", &temp);
		bucket[temp]++;
	}
	
	for(i = 1; i <= MAX; i++) { if(bucket[i]) { // 約数の一覧表を作る
		int m = i;
		while(m <= MAX) {
			div_table[m][ div_num[m] ] = i;
			div_num[m]++;
			m += i;
		}
	} }
	
	i = 1;
	while(i < n) {
		if(div_num[pre]) { // preの約数が残ってれば、その中で一番小さいやつ
			j = 0;
			while(bucket[ div_table[pre][j] ] == 0) { j++; }
			pre = div_table[pre][j];
		} else {
			int min = MAX * MAX, p = -1;
			for(j = 1; j <= MAX; j++) {
				if(bucket[j] && div_num[j] == 1) { // 自身以外にも約数が残ってるやつは見なくていい
					int l = lcm(pre, j);
					if(l < min) { min = l; p = j; }
				}
			}
			pre = p;
		}
		printf("%d ", pre);
		i++;
		bucket[pre]--;
		if(bucket[pre] == 0) { // preが0個になっていたら、preの倍数の「残りの約数の個数」を更新
			int m = pre;
			while(m <= MAX) {
				div_num[m]--;
				m += pre;
			}
		}
	}
	printf("\n");
	
	return 0;
}

int gcd(int x, int y) {
	int max = (y < x) ? x : y;
	int min = (x < y) ? x : y;
	if(min == 0) { return max; }
	return gcd(min, max % min);
}

int lcm(int x, int y) {
	return x * y / gcd(x, y);
}
0