網易-分蘋果
阿新 • • 發佈:2018-11-02
題目描述
n 只奶牛坐在一排,每個奶牛擁有 ai 個蘋果,現在你要在它們之間轉移蘋果,使得最後所有奶牛擁有的蘋果數都相同,每一次,你只能從一隻奶牛身上拿走恰好兩個蘋果到另一個奶牛上,問最少需要移動多少次可以平分蘋果,如果方案不存在輸出 -1。
輸入描述:
每個輸入包含一個測試用例。 每個測試用例的第一行包含一個整數 n(1 <= n <= 100), 接下來的一行包含 n 個整數 ai(1 <= ai <= 100)。
輸出描述:
輸出一行表示最少需要移動多少次可以平分蘋果,如果方案不存在則輸出 -1。
示例1
輸入
4
7 15 9 5
輸出
3
題解:
#include <iostream> #include <vector> using namespace std; int main(){ int n; while (cin >> n){ vector<int> a(n, 0); int sum = 0; for (int i = 0; i < n; i++){ cin >> a[i]; sum += a[i]; } if (sum % n != 0){ cout << "-1" << endl; } else { bool isOk = true; int avg = sum / n; int cnt = 0; for (int i = 0; i < n; i++){ if ((a[i] - avg) % 2 != 0){ cout << "-1" << endl; isOk = false; break; } } if (isOk == true){ for (int i = 0; i < n; i++){ if (a[i] - avg > 0){ cnt += (a[i] - avg) / 2; } } cout << cnt << endl; } } } return 0; }