Distribute apples

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.

 1 package ceshi;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStreamReader;
 5 
 6 public class Tee {
 7     public static void main(String[] args) throws Exception {
 8          BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
 9             String s = bf.readLine();
10             int n=0;
11             try{
12                 n=Integer.parseInt(s);
13             }catch(Exception e){
14                 System.err.print("输入纯数字");
15             }
16             int[] str=new int[n];
17             int num=0;
18            String[] str1=bf.readLine().split(" ");
19            for (int i=0;i<str1.length;i++) {
20             str[i]=Integer.parseInt(str1[i]);
21             num+=str[i];
22         }
23             if(num%n!=0){
24                 System.out.println(-1);
25             }else{
26                 int cs=num/n;
27                 boolean boo=true;
28                 int zs=0;
29                 if(cs%2==0){
30                     for(int i=0;i<str.length;i++){
31                         if(str[i]%2!=0){
32                             boo=false;
33                             break;
34                         }
35                         if(str[i]>cs){
36                             zs+=(str[i]-cs)/2;
37                         }
38                     }
39                 }else{
40                     for(int i=0;i<str.length;i++){
41                         if(str[i]%2==0){
42                             boo=false;
43                             break;
44                         }
45                         if(str[i]>cs){
46                             zs+=(str[i]-cs)/2;
47                         }
48                     }
49                 }
50                 if(boo){
51                     System.out.println(zs);
52                 }else{
53                     System.out.println(-1);
54                 }
55             }
56            
57     }
58 }

 

Guess you like

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