分配苹果

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

 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 }

猜你喜欢

转载自www.cnblogs.com/4545mdf/p/8990619.html