n 只奶牛坐在一排,每个奶牛拥有 ai 个苹果,现在你要在它们之间转移苹果,使得最后所有奶牛拥有的苹果数都相同,每一次,你只能从一只奶牛身上拿走恰好两个苹果到另一个奶牛上,问最少需要移动多少次可以平分苹果,如果方案不存在输出 -1。
输入描述:
每个输入包含一个测试用例。每个测试用例的第一行包含一个整数 n(1 <= n <= 100),接下来的一行包含 n 个整数 ai(1 <= ai <= 100)。输出描述:
输出一行表示最少需要移动多少次可以平分苹果,如果方案不存在则输出 -1。输入例子:
4
7 15 9 5输出例子:
3
#include <iostream>
#include <numeric>
#include<algorithm>
#include <string>
#include<hash_map>
#include <set>
using namespace std;
//#define debug_
int func(vector<int>& vec)
{
int sum;
double avg;
sum = accumulate(vec.begin(), vec.end(), 0);
avg = (double)sum / (double)vec.size();
if (avg != (int)avg)
{
return -1;
}
int count(0);
for (auto i = 0; i < vec.size();++i)
{
if (vec[i] > avg)
{
while (vec[i] > avg)
{
vec[i] -= 2;
count++;
}
}
else if (vec[i]<avg)
{
while (vec[i]<avg)
{
vec[i] += 2;
count++;
}
}
if (vec[i]!=avg)
{
return -1;
}
}
return count / 2;
}
int main()
{
int n;
vector<int> vec;
#ifdef debug_
n = 4;
vec.push_back(7);
vec.push_back(15);
vec.push_back(9);
vec.push_back(5);
#else
cin>>n;
vec.resize(n);
for(auto i = 0;i<n;++i)
{
cin>>vec[i];
}
#endif
cout << func(vec) << endl;
return 0;
}