求平均问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35747066/article/details/89293832

题目描述

n 只奶牛坐在一排,每个奶牛拥有 ai 个苹果,现在你要在它们之间转移苹果,使得最后所有奶牛拥有的苹果数都相同,每一次,你只能从一只奶牛身上拿走恰好两个苹果到另一个奶牛上,问最少需要移动多少次可以平分苹果,如果方案不存在输出 -1。

输入描述:

每个输入包含一个测试用例。每个测试用例的第一行包含一个整数 n(1 <= n <= 100),接下来的一行包含 n 个整数 ai(1 <= ai <= 100)。

输出描述:

输出一行表示最少需要移动多少次可以平分苹果,如果方案不存在则输出 -1。

示例1

输入

4
7 15 9 5

输出

3
#include<vector>
#include<iostream>
#include<cmath>
#include<numeric>
using namespace std;
int main(){
    int n;int Result = 0;int avg = 0;
    int FLAG = 0;
    scanf("%d",&n);
    vector<int> Input;
    for(int i = 0;i < n;i ++){
        int tmp;
        scanf("%d",&tmp);
        Input.push_back(tmp);
    }
    int sum = accumulate(Input.begin(),Input.end(),0);
    if(sum % n != 0){//sum不能被4整除
        FLAG = 1;
    }
    else{
        avg = sum / n;
    }
    for(int i = 0;i < n;i ++){
        if((Input[i] - avg) % 2 != 0){
            FLAG = 1;
        }
        else{
            Result += abs(Input[i] - avg) / 2;
        }
    }
    if(FLAG == 1){
        printf("1\n");
    }
    else{printf("%d\n",Result / 2);}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35747066/article/details/89293832