題目連結

https://zerojudge.tw/ShowProblem?problemid=a737

https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=982

參考文章

本題要點

根據數學魔法得知,中位數會與所有點的距離和最小

所以只要找到數列當中的中位數,就是老大的家了

接下來再用迴圈跑一次算所有親戚家到老大家距離和,就是答案了~

特別留意中位數在長度 奇/偶 數的計算方式是不同的!!

參考解答

解一:

截圖 2024-06-23 下午2.17.13.png

n = int(input())
for _ in range(n):
	neighbor = list(map(int, input().split()))
	neighbor.remove(neighbor[0])
	neighbor.sort()

	# 找中位數(老大家)
	NL = len(neighbor)
	if NL % 2: # 奇數長度
		home =  neighbor[NL // 2]
	else:
		home =  (neighbor[NL // 2 - 1] + neighbor[NL // 2]) / 2

	# 計算每個親戚門牌到老大家的距離
	result = 0
	for location in neighbor:
		result += abs(location - home)
	print(int(result))

回CPE頁面

CPE