Codeforces 1742A Sum 總和

題目說明

難易度 : 800

英文原文如下

You are given three integers a, b, and c. Determine if one of them is the sum of the other two.

中文翻譯

給予您三個整數 a, b, 跟 c。判斷他們其中一個是不是由另外兩個所組成。

輸入

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

The description of each test case consists of three integers a, b, c(0≤a,b,c≤20).

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

每一個測試案例由三個整數 a, b, c 組成 (0≤a,b,c≤20)

輸出

For each test case, output “YES” if one of the numbers is the sum of the other two, and “NO” otherwise.

You can output the answer in any case (for example, the strings “yEs”, “yes”, “Yes” and “YES” will be recognized as a positive answer).

針對每個測試案例,要是其中一個數字是另外兩個總和,印出 “YES”,反之則印出 “NO”

你可以印出答案而不需在意大小寫(舉例來說,字串 “yEs”, “yes”, “Yes” 跟”YES”會被同樣視為正向的答覆)

範例

輸入7
1 4 3
2 5 8
9 11 20
0 0 0
20 20 20
4 12 3
15 7 8
輸出YES
NO
YES
YES
NO
NO
YES

筆記

In the first test case, 1+3=4.

In the second test case, none of the numbers is the sum of the other two.

In the third test case, 9+11=20.

在第一個例子中,1+3=4。

在第二個例子中,沒有一個數字可以由另外兩個數字組成。

第三個例子,9+11=20。


解題思路

在我們的解法中,我們使用了兩個變數 tmp1 以及 tmp2 來代表第三個元素可能得值

tmp1 的話是 第三個元素剛好是前兩個的總和

tmp2 的話 就是第三個元素與前兩個的較小數組成較大的那個

而要是第三個元素不是這兩個其中之一,就代表著沒辦法達成題目的條件

C#解決方案

方案1

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

for(int i=0; i<n; i++){
    int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    
    var tmp1 = arr[0]+arr[1];
    var tmp2 = arr[0]>arr[1]?arr[0]-arr[1]:arr[1]-arr[0];

    
    Console.WriteLine(arr[2]==tmp1 || arr[2]==tmp2?"YES":"NO");
}

當然,如果懶的判斷,我們也可以先Sort,再來判斷前兩個元素加總是否為第三個元素就好

方案2

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

for(int i=0; i<n; i++){
    int[] arr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
    Array.Sort(arr);
    
    bool res = arr[2]-arr[1]-arr[0] == 0;
    Console.WriteLine(res?"YES":"NO");
}

不過,隨之伴隨來的當然就是較差的時間複雜度 Array.Sort 本身就是 O(n log n)

Klook.com

結論

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

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

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

題目連結 : Problem – 1742A – Codeforces

一些其他的Codeforces文章

發佈留言

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