結果

問題 No.14 最小公倍数ソート
ユーザー warashiwarashi
提出日時 2015-11-02 21:58:22
言語 Go
(1.22.1)
結果
TLE  
実行時間 -
コード長 1,393 bytes
コンパイル時間 12,010 ms
コンパイル使用メモリ 221,068 KB
実行使用メモリ 21,440 KB
最終ジャッジ日時 2024-04-19 03:31:15
合計ジャッジ時間 17,446 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

package main

import (
	"fmt"
)

type iv struct {
	index, value int
}

func factor(n int) (f []int) {
	for i := 1; i*i <= n; i++ {
		if n%i == 0 {
			f = append(f, i)
			f = append(f, n/i)
		}
	}
	return
}

func main() {
	var N int
	fmt.Scan(&N)
	a := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scan(&a[i])
	}

	if len(a) > 1 {
		lcmSort(a[0], a[1:])
	}
	ans := fmt.Sprintln(a)
	fmt.Println(ans[1 : len(ans)-2])
}

func lcmSort(key int, a []int) {
	if len(a) == 1 {
		return
	}

	f := factor(key)
	m := make(map[int][]iv)
	for i, v := range a {
		for _, d := range f {
			if v%d == 0 {
				m[d] = append(m[d], iv{i, v})
			}
		}
	}
	t := make([]iv, 0, len(m))
	for _, v := range m {
		t = append(t, min(v))
	}
	i := lcmMinIndex(key, t)
	a[0], a[i] = a[i], a[0]

	lcmSort(a[0], a[1:])
}
func lcmMinIndex(key int, a []iv) (m int) {
	for i := range a {
		if less(key, a, i, m) {
			m = i
		}
	}
	return a[m].index
}
func min(a []iv) (m iv) {
	m.value = 10000
	for _, v := range a {
		if v.value < m.value {
			m = v
		}
	}
	return
}
func less(key int, a []iv, i, j int) bool {
	lcmi := lcm(key, a[i].value)
	lcmj := lcm(key, a[j].value)
	if lcmi == lcmj {
		return a[i].value < a[j].value
	}
	return lcmi < lcmj
}
func lcm(a, b int) int {
	g := gcd(a, b)
	return (a / g) * (b / g) * g
}

func gcd(a, b int) int {
	if a > b {
		a, b = b, a
	}
	if a == 0 {
		return b
	}

	return gcd(b%a, a)
}
0