杭电1280java实现

前m大的数:
Problem Description
还记得Gardon给小希布置的那个作业么?(上次比赛的1005)其实小希已经找回了原来的那张数表,现在她想确认一下她的答案是否正确,但是整个的答案是很庞大的表,小希只想让你把答案中最大的M个数告诉她就可以了。
给定一个包含N(N<=3000)个正整数的序列,每个数不超过5000,对它们两两相加得到的N*(N-1)/2个和,求出其中前M大的数(M<=1000)并按从大到小的顺序排列。

Input
输入可能包含多组数据,其中每组数据包括两行:
第一行两个数N和M,
第二行N个数,表示该序列。

Output
对于输入的每组数据,输出M个数,表示结果。输出应当按照从大到小的顺序排列。

Sample Input
4 4
1 2 3 4
4 5
5 3 6 4

Sample Output
7 6 5 5
11 10 9 9 8
刚开始想用hashset却发现里面有重复值。后来想用list,虽然能够实现操作。但是一直超时,因为超内存,后来想了下,list每次增加的时候都会申请一个新的数组,如果数据过多肯定会爆内存,后来使用大数组粗存,每次只使用其中的前一部分,并且也支持排序只排前一部分,以前还没见到过这张的处理,记录下来。是对list和数组都增加了理解。
代码如下:


import java.util.Arrays;
import java.util.Scanner;
public class 杭电1280 {
    static int a[]=new int[3002];
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);      
        int b[]=new int[5000000];       
        while(sc.hasNext())
        {
          int n=sc.nextInt();//数据个数
          int m=sc.nextInt();//前m大

          int number=0;
          for(int i=0;i<n;i++)
          {
              a[i]=sc.nextInt();
          }
          for(int i=0;i<n;i++)
          {
              for(int j=i+1;j<n;j++)
              {
                b[number++]=(a[i]+a[j]);
              }
          }
          Arrays.sort(b, 0, (n-1)*n/2);
          int x=number-1;
          for(int i=0;i<m;i++)
          {
              if(i==m-1)System.out.println(b[x-i]);
              else
          System.out.print(b[x-i]+" ");
          }

        }
    }
}

ps:注意输出格式,空格和换行。

猜你喜欢

转载自blog.csdn.net/qq_40693171/article/details/80100863