Divide apples (find the pattern)

Topic description

n cows are sitting in a row, each cow has a i  apples, now you want to transfer apples between them so that in the end all cows have the same number of apples, each time, you can only take from one cow Walk exactly two apples to another cow, ask the minimum number of moves required to divide the apples equally, and output -1 if the solution does not exist.

Enter description:

Each input contains a test case. The first line of each test case contains an integer n (1 <= n <= 100), the next line contains n integers a
i
(1 <= ai <= 100)。

Output description:

One line of output indicates the minimum number of moves required to divide the apple, or -1 if the solution does not exist.
Example 1

enter

4
7 15 9 5

output

3
1  import java.util.Scanner;
 2  
3  /** 
4  * divided apples 
 5  * 1, or the direct average is not an integer, you can not get
 6  * 2, each move two will not change the parity if the average and each If the value parity is different, you can't get it, 
 7  * 3, then divide the average value as the dividing line to calculate the number of times that the value less than the average changes to the average
 8  * 
 9  * @author Dell
 10  *
 11  *
 12  * 4 7 15 9 5
 13   */ 
14  public  class Main {
 15      static  public  int n = 4 ;
 16      static  public  int [] num; //= {7,15,9,5};
17     static public int sum;
18     static public int avg;
19     static public double avgDouble;
20     static public int count;
21 //    static {
22 //        for (int i = 0; i < num.length; i++) {
23 //            sum += num[i];
24 //        }
25 //        avg = sum / n;
26 //    }
27 
28     static public int f() {
29         if (avgDouble!=avg) {
30             return -1;
31         }
32         for (int i = 0; i < num.length; i++) {
33             if ((num[i] - avg) % 2 == 0/*奇偶性*/) {
34                 int t = (num[i] - avg) / 2;
35                 if (t > 0) {
36                     count += t;
37                 }
38             } else {
39                 return -1;
40             }
41         }
42         return count;
43     }
44 
45     public static void main(String[] args) {
46         Scanner sc = new Scanner(System.in);
47         n = sc.nextInt();
48         num = new int[n];
49         for (int i = 0; i < num.length; i++) {
50             num[i] = sc.nextInt();
51             sum+=num[i];
52             
53         }
54         avgDouble = (sum*1.0)/n;
55         avg = (int)avgDouble;
56         System.out.println(f());
57 
58     }
59 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325141520&siteId=291194637