Codeforces 1692A Marathon 馬拉松

題目說明

難易度 : 800

英文原文如下

You are given four distinct integers a, b, c, d.

Timur and three other people are running a marathon. The value a is the distance that Timur has run and b, c, d correspond to the distances the other three participants ran.

Output the number of participants in front of Timur.

中文翻譯

給予你 4 個獨立的整數 a, b, c, d

Timur 跟另外三人正在參與一場馬拉松中。 a 是 Timur 已經跑的距離,而 b, c, d 則表示了另外三位參賽者跑的距離。

輸出在 Timur 前面的參賽者一共有幾位。

輸入

The first line contains a single integer t (1≤t≤104) — the number of test cases.

The description of each test case consists of four distinct integers a, b, c, d (0≤a,b,c,d≤104).

第一行包含了一個整數 t (1≤t≤104) — 測試案例的數量

每一個測試案例都由 4 個獨立的整數組成 a, b, c, d (0≤a,b,c,d≤104)。

輸出

For each test case, output a single integer — the number of participants in front of Timur.

針對每個測試案例,輸出一個整數 — Timur前面的參賽者(跑得比他還遠的)

範例

輸入4
2 3 4 1
10000 0 1 2
500 600 400 300
0 9999 10000 9998
輸出2
0
1
3

筆記

For the first test case, there are 2 people in front of Timur, specifically the participants who ran distances of 3 and 4. The other participant is not in front of Timur because he ran a shorter distance than Timur.

For the second test case, no one is in front of Timur, since he ran a distance of 10000
while all others ran a distance of 0, 1, and 2 respectively.

For the third test case, only the second person is in front of Timur, who ran a total distance of 600 while Timur ran a distance of 500.

在第一個測試案例中,有兩個人在 Timur 前面,分別是跑了3以及4距離的參賽者,而唯一一位不在 Timur 前面的參賽者則是因為他跑得比 Timur 還要少的距離。

第二個測試案例中,沒有人在 Timur 前面,因為他跑了10000 的距離 ,而其他人分別是 0、1、2而已

第三個測試案例中,只有第二個人跑在 Timur 前面,就是那個總共跑了600的距離的而Timur 只跑了 500


解題思路

有幾種方式可以解決這一題,就讓我們來看一下吧

然後來比較一下各自的寫法或是限制

C# 解決方案

方案1 – for 迴圈

int t = int.Parse(Console.ReadLine());

for(int i=0; i<t; i++){
    int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    int cnt = 0;
    int timur = arr[0];
    
    for(int j=1;j<arr.Length;j++){
        if(arr[j]>timur){
            cnt++;
        }
    }
    Console.WriteLine(cnt);
}

最常見的作法,迴圈判斷是否大於並加在計數器上

方案2

int t = int.Parse(Console.ReadLine());

for(int i=0; i<t; i++){
    int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    int cnt = 0;
    
    cnt+=arr[1]>arr[0]?1:0;
    cnt+=arr[2]>arr[0]?1:0;
    cnt+=arr[3]>arr[0]?1:0;
    
    Console.WriteLine(cnt);
}

已知只有4位參賽者,故也可以用3個三元不等式來判斷,當然如果數量大的話就非常不適合了

方案3 – LINQ

int t = int.Parse(Console.ReadLine());

for(int i=0; i<t; i++){
    int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    int timur = arr[0];
    
    var cnt = arr.Count(x=>x>timur);
    
    Console.WriteLine(cnt);
}

用 LINQ 的 Count 搭配條件就可以非常簡單的解決,是我非常推薦的作法

Klook.com

結論

有機會真的想去跑跑看路跑呢,但在台北舉辦的時間都超早的ㄟ!!

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

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

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

題目連結 : Problem – 1692A – Codeforces

一些其他的Codeforces文章

發佈留言

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