Codeforces 228A Is your horseshoe on the other hoof? 你的馬蹄鐵在另一支腳上嗎

難易度 : 800

英文原文如下

Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.

Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.

中文翻譯

Valera 這匹馬要和朋友們一起參加派對。他一直在追蹤時尚潮流,知道穿上四隻不同顏色的馬蹄鐵很受歡迎。Valera 留下了去年的四隻馬蹄鐵,但也許其中一些顏色相同。在這種情況下,他需要去商店購買一些額外的馬蹄鐵,以免在他時尚的同伴面前丟臉。

幸運的是,商店出售各種色彩的馬蹄鐵,而 Valera 有足夠的錢可以買任何四隻。然而,為了省錢,他想要花費盡可能少的錢,所以你需要幫助 Valera 確定他需要購買的馬蹄鐵的最小數量,以便在派對上穿上四隻不同顏色的馬蹄鐵。

輸入

The first line contains four space-separated integers s1, s2, s3, s4 (1 ≤ s1, s2, s3, s4 ≤ 109) — the colors of horseshoes Valera has.

Consider all possible colors indexed with integers.

第一行包含了 4 個用空白間隔的整數 s1, s2, s3, s4 (1 ≤ s1, s2, s3, s4 ≤ 109) — Valera 現在有的馬蹄鐵顏色

考慮所有可能的顏色,用整數進行索引。

輸出

Print a single integer — the minimum number of horseshoes Valera needs to buy.

印出一個單獨的整數— Valera 需要買的馬蹄鐵數量。

範例

輸入1 7 3 3
輸出1

有 1 7 3這三種顏色了,所以再買一個顏色就好

輸入7 7 7 7
輸出3

只有 7 這一種顏色,故還要買三個顏色


解題思路

在這個問題中,其實也比較單純

就是要在輸入去找Distinct的數量,然後要是不滿4個就要補給它這樣

C#解決方案

方案1 – HashSet

string[] arr = Console.ReadLine().Split(' ').ToArray();
HashSet<string> hSet = new HashSet<string>();

foreach(var i in arr){
    hSet.Add(i);
}

int res = 4 - hSet.Count;
Console.WriteLine(Math.Max(0,res));

利用了HashSet唯一的特性 (有過的元素再 Add 是不會加入的)

方案2 – LINQ

string[] arr = Console.ReadLine().Split(' ').ToArray();


int res = 4 - arr.Distinct().Count();
Console.WriteLine(Math.Max(0,res));

LINQ就簡單多了,直接Distinct 跟 Count 就能達到同樣的效果 (不過該題出的時候可能還沒有LINQ呢…)


結論

其實究竟要翻成馬的鞋子還是馬蹄鐵讓我思考了好一陣子…

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

🧡分享文章或是留一個言,那都是對我的支持

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

題目連結 : Problem – 228A – Codeforces

一些其他的Codeforces文章

發佈留言

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