C++程式檢查是否可以分配糖果袋,使得兩位朋友獲得相同數量的糖果
假設我們有一個包含4個元素的陣列A。有4袋糖果,第i袋包含A[i]數量的糖果。我們想把每袋糖果送給我們的兩個朋友中的一個。我們必須檢查是否可以以這樣的方式分配這些糖果袋,使得每個朋友總共收到相同數量的糖果?
因此,如果輸入類似於A = [1, 7, 11, 5],則輸出將為True,因為我們可以將第一個和第三個糖果袋送給第一個朋友,將第二個和第四個糖果袋送給第二個朋友。這樣,每個朋友將收到12顆糖果。
步驟
為了解決這個問題,我們將遵循以下步驟 -
a := A[0] b := A[1] c := A[2] d := A[3] if (a + b) is same as (c + d) or (a + c) is same as (b + d) or (a + d) is same as (b + c) or (a + b + c) is same as d or (a + b + d) is same as c or (a + c + d) is same as b or (b + c + d) is same as a, then: return true Otherwise return false
示例
讓我們看看以下實現以獲得更好的理解 -
#include <bits/stdc++.h> using namespace std; bool solve(vector<int> A) { int a = A[0]; int b = A[1]; int c = A[2]; int d = A[3]; if (a + b == c + d || a + c == b + d || a + d == b + c || a + b + c == d || a + b + d == c || a + c + d == b || b + c + d == a) return true; else return false; } int main() { vector<int> A = { 1, 7, 11, 5 }; cout << solve(A) << endl; }
輸入
1, 7, 11, 5
輸出
1
廣告