牛客网在线编程:分苹果

题目描述:

n 只奶牛坐在一排,每个奶牛拥有 ai 个苹果,现在你要在它们之间转移苹果,使得最后所有奶牛拥有的苹果数都相同,每一次,你只能从一只奶牛身上拿走恰好两个苹果到另一个奶牛上,问最少需要移动多少次可以平分苹果,如果方案不存在输出 -1。
输入描述:
每个输入包含一个测试用例。每个测试用例的第一行包含一个整数 n(1 <= n <= 100),接下来的一行包含 n 个整数 ai(1 <= ai <= 100)。
输出描述:
输出一行表示最少需要移动多少次可以平分苹果,如果方案不存在则输出 -1。
示例1
输入

4
7 15 9 5
输出

3

思路:

数学问题,依次判断即可。首先输入的是n个奶牛,然后输入一行每个奶牛的苹果数。
计算所有奶牛拥有的苹果总数,平均数。总数不能整除奶牛数则返回-1
依次判断每个奶牛拥有的苹果是否大于平均数,大于的判断超出的值是否能整除2,不能则返回-1
能则将超出的数加起来,除以2即为需要转移的次数

 1 import java.util.*;
 2 public class Fenpingguo {
 3 
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         Scanner sc = new Scanner(System.in);
 7         int n = sc.nextInt();
 8         int num = 0;
 9         int[] ai = new int[100];
10         for(int i = 0; i < n; i++){
11             ai[i] = sc.nextInt();
12             num+=ai[i];
13         }
14         int x = num/n;
15         int key = 0;
16         int over = 0;
17         for(int i = 0; i < n; i++){
18             if(ai[i]>x){
19                 over = ai[i]-x;
20                 if(over%2!=0){
21                     System.out.println(-1);
22                     return;
23                 }
24                 key+=ai[i]-x;
25             }
26         }
27         if(num%n!=0) System.out.println(-1);
28         //else if(key%2!=0) System.out.println(-1);
29         else {
30             System.out.println(key/2);
31         }
32     }
33 
34 }
原文地址:https://www.cnblogs.com/zlz099/p/8520901.html