Codeforces 723A The New Year: Meeting Friends 新年: 見朋友

題目說明

難易度 : 800

英文原文如下

There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?

It’s guaranteed that the optimal answer is always integer.

中文翻譯

有三個朋友住在 Lineland(線大陸)上的一條直線 Ox 上。第一個朋友住在 x1 這一個點上,第二個朋友則是住在  x2 ,第三個朋友  x3。 他們計劃要一起慶祝新年,所以他們需要約在其中一個點上見面。那他們為了慶祝新年而見一面所需要移動的最小總距離會是多少呢?

最佳的答案保證永遠都是整數。

輸入

The first line of the input contains three distinct integers x1x2 and x3 (1 ≤ x1, x2, x3 ≤ 100) — the coordinates of the houses of the first, the second and the third friends respectively.

輸入的第一行包含了三個獨立的整數 x1x2 跟 x3 (1 ≤ x1, x2, x3 ≤ 100) — 分別代表了三位朋友房子的座標。

輸出

Print one integer — the minimum total distance the friends need to travel in order to meet together.

印出一個整數  — 朋友們為了見到彼此所需要移動的最小總距離。

範例

輸入7 1 4
輸出6
輸入30 20 10
輸出20

筆記

In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4.

在第一個範例中,朋友們需要在點4上見面,為此,第一個朋友需要移動3個單位(從點7到點4),第二個朋友需要移動3個單位(從點1到點4),第三個朋友則不需移動,因為他本來就住在點4上。


解題思路

在我們的解法中,我們需要先找到位於中間的朋友,那就會是見面的地點,並讓兩側的朋友往他的方向移動。

最簡單的作法,就是對陣列排序後再判斷~ 我這裡偷懶就直接用內建的排序了

C#解決方案

方案1

int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
Array.Sort(arr);

Console.WriteLine(arr[1]-arr[0]+arr[2]-arr[1]);

結論

🧡如果文章有幫上你的忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Problem – 723A – Codeforces

一些其他的Codeforces文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *