# これが1種類にまとめるのであればmedianだろう # ということはYをソートして、前から何個目までを1グループ目とするかで探索 # 1グループ目は1グループ目のmedianに、2グループ目は2グループ目のmedianに # その最低値が答えか # 二重ループでTLE # 三分探索で最低値を探す N = int(input()) Y = list(map(int, input().split())) Y.sort() from math import floor, ceil def cost_calc(group1_len): group2_len = N - group1_len if group1_len%2 == 1: median1 = Y[group1_len//2] else: median1 = floor((Y[group1_len//2-1]+Y[group1_len//2])/2) if group2_len%2 == 1: median2 = Y[group1_len + group2_len//2] else: median2 = floor((Y[group1_len + group2_len//2-1]+Y[group1_len + group2_len//2])/2) if median2 == median1: median2 += 1 calc = 0 for i in range(group1_len): calc += abs(Y[i]-median1) for i in range(group1_len, N): calc += abs(Y[i]-median2) return calc if N < 100: ans = 10**10 for group1_end in range(N-1): group1 = Y[:group1_end+1] group1_len = group1_end+1 group2 = Y[group1_end+1:] group2_len = N - group1_len if group1_len%2 == 1: median1 = Y[group1_len//2] else: median1 = floor((Y[group1_len//2-1]+Y[group1_len//2])/2) if group2_len%2 == 1: median2 = Y[group1_len + group2_len//2] else: median2 = floor((Y[group1_len + group2_len//2-1]+Y[group1_len + group2_len//2])/2) if median2 == median1: median2 += 1 cost = 0 for i in range(group1_len): cost += abs(Y[i]-median1) for i in range(group1_len, N): cost += abs(Y[i]-median2) ans = min(ans, cost) #print(group1, group2) #print(group1_len, group2_len, median1, median2, cost) #print() print(ans) else: # 谷、つまり1極値を求める三分探索での解き方 # https://roiti46.hatenablog.com/entry/2015/04/29/yukicoder_No.198_%E3%82%AD%E3%83%A3%E3%83%B3%E3%83%87%E3%82%A3%E3%83%BC%E3%83%BB%E3%83%9C%E3%83%83%E3%82%AF%E3%82%B9%EF%BC%92 # https://qiita.com/ganyariya/items/1553ff2bf8d6d7789127 # 範囲に注意、ギリギリありえない値とする left, right = 0, N-1 while right-left > 2: left_mid, right_mid = (2*left+right)//3, (left+2*right)//3 if cost_calc(left_mid) <= cost_calc(right_mid): # 右midの方が大きいから右を右midに変える right = right_mid else: left = left_mid #print(left_mid, right_mid) ans = min(cost_calc(left_mid), cost_calc(right_mid)) # leftとrightの間も入れる必要あるのか? print(ans)