贪心算法经典例题

2019网易提前批题

小易有一些立方体,每个立方体的边长为1,他用这些立方体搭了一些塔。
现在小易定义:这些塔的不稳定值为它们之中最高的塔与最低的塔的高度差。
小易想让这些塔尽量稳定,所以他进行了如下操作:每次从某座塔上取下一块立方体,并把它放到另一座塔上。
注意,小易不会把立方体放到它原本的那座塔上,因为他认为这样毫无意义。
现在小易想要知道,他进行了不超过k次操作之后,不稳定值最小是多少。

输入描述:
第一行两个数n,k (1 <= n <= 100, 0 <= k <= 1000)表示塔的数量以及最多操作的次数。
第二行n个数,ai(1 <= ai <= 104)表示第i座塔的初始高度。


输出描述:
第一行两个数s, m,表示最小的不稳定值和操作次数(m <= k)
接下来m行,每行两个数x,y表示从第x座塔上取下一块立方体放到第y座塔上。

输入例子1:
3 2
5 8 5

输出例子1:
0 2
2 1
2 3用贪心算法:每次在最高的塔中拿一个出来加到最低的塔上面去
 

package wangyi;

import java.util.ArrayList;
import java.util.Scanner;

public class main{
   public static void main(String[] args) {
      ArrayList<int[]> res=new ArrayList<>();
      Scanner in = new Scanner(System.in);
      int n=in.nextInt();
      int k=in.nextInt();
      int[] hights=new int[n];
      for(int i=0;i<n;i++){
          hights[i]=in.nextInt();
      }
      int lowIndex=0;
      int highIndex=0;
      for(int i=0;i<k;i++){
          highIndex=find_high(hights);
          lowIndex=find_low(hights);
          if(hights[highIndex]== hights[lowIndex]){
              break;
          }
          hights[highIndex]=hights[highIndex]-1;
          hights[lowIndex]=hights[lowIndex]+1;
          int[] banyun=new int[2];
          banyun[0]=highIndex+1;
          banyun[1]=lowIndex+1;
          res.add(banyun);
      }
      highIndex=find_high(hights);
      lowIndex=find_low(hights);
      System.out.println(hights[highIndex]-hights[lowIndex]+" "+res.size());
      for(int i=0;i<res.size();i++){
              System.out.println(res.get(i)[0]+" "+res.get(i)[1]);          
      }
   }
   
   public static int find_high(int[] hights) {
       int maxIndex=0;
       int max=0;
       for(int i=0;i<hights.length;i++){
         if(hights[i]>max){
             max=hights[i];
             maxIndex=i;
         }
       }
       return maxIndex;
   }
   
   public static int find_low(int[] hights) {
       int minIndex=0;
       int min=Integer.MAX_VALUE;
       for(int i=0;i<hights.length;i++){
         if(hights[i]<min){
             min=hights[i];
             minIndex=i;
         }
       }
       return minIndex;
   }
}

猜你喜欢

转载自blog.csdn.net/sofuzi/article/details/81675814