Codeforces 158A 下一輪 – 翻譯與解答

難易度 : 800

英文原文如下

“Contestant who earns a score equal to or greater than the k-th place finisher’s score will advance to the next round, as long as the contestant earns a positive score…” — an excerpt from contest rules.

A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many participants will advance to the next round.

中文翻譯

“得分等於或高於第 k 名得分者的參賽者將晉級下一輪,只要該參賽者獲得的分數為正數(>0)…” — 來自比賽規則的一部分。

總共 n 位參賽者參加這個比賽(n ≥ k),然後你已經知道他們全部的分數。計算多少個人會晉級到下一輪。

輸入

The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 50) separated by a single space.

The second line contains n space-separated integers a1, a2, …, an (0 ≤ ai ≤ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai ≥ ai + 1).

輸入的第一行包含了兩個整數 n 跟 k,它們之間以一個空白隔開。

在第二行則包含了 n 個以空白隔開的整數 a1, a2, …, an (0 ≤ ai ≤ 100), ai  就是第 i 名參賽者得到的成績。給定的序列是非遞增的(也就是說,對於所有 i 從 1 到 n – 1,以下條件都是成立的:aiai+1)。

輸出

Output the number of participants who advance to the next round.

輸出可以晉級下一輪的參賽者的總數。

範例

輸入8 5
10 9 8 7 7 7 5 5
輸出6
輸入4 2
0 0 0 0
輸出0

筆記

In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.

In the second example nobody got a positive score.

在第一個範例中,排名第五的參賽者得了7分,但因為第六的參賽者也得了7分,所以共有6個人晉級下一輪。

在第二個範例中,沒有人得超過0分。


解題思路

在這一題中,我的解決方式有兩種,第一次的是直接使用字串比較來判斷

第二次的才是用數字計算

C#解決方案

⚠️方案1 > 不用數字來檢查的方式

string[] first = Console.ReadLine().Split(' '); //split by space
int n = int.Parse(first[0]); 
int k = int.Parse(first[1]); 

string[] ans = Console.ReadLine().Split(' '); //split by space
string chk = ans[k-1];
int add = 0;

if(chk=="0"){
    for(int i=0;i<k;i++)
    {
        if(ans[i]!="0")
        {
            add+=1;
        } else {
            break;
        }
    }
} else{
    add = k;
    
    for(int i=k;i<n;i++)
    {
        if(ans[i]==chk)
        {
            add+=1;
        }
    }   
}
Console.WriteLine(add); 

在我的第一個解決方案中,我解決了這個問題,而不需要將分數轉換為數字。

根據第 k 名參賽者的分數(chk),程式執行不同的操作:

如果第 k 名參賽者的分數為 0(chk==”0″),程式會遍歷前 k 名參賽者的分數並計算具有非零分數的參賽者數量,將其存儲在變數 add 中。如果它遇到分數為 0 的參賽者,則退出循環。

如果第 k 名參賽者的分數不為 0,程式會將 add 設置為 k,表示前 k 名參賽者肯定會晉級。然後,它遍歷第 k 位之後的所有參賽者,計算分數等於 chk 的參賽者數量,並將它們添加到 add 變數中。


結論

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

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

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

題目連結 : Problem – 158A – Codeforces

一些其他的文章

發佈留言

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