2013
12-12

九度-1034-寻找大富翁[解题代码]

浙江桐乡乌镇共有n个人,请找出该镇上的前m个大富翁.

输入包含多组测试用例.
每个用例首先包含2个整数n（0<n<=100000）和m(0<m<=10)，其中: n为镇上的人数，m为需要找出的大富翁数, 接下来一行输入镇上n个人的财富值.
n和m同时为0时表示输入结束.

请输出乌镇前m个大富翁的财产数，财产多的排前面，如果大富翁不足m个，则全部输出,每组输出占一行.

3 1
2 5 -1
5 3
1 2 3 4 5
0 0

5
5 4 3

java 代码如下：
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

static int arr[] = new int[100001];
static int n,m;

static PrintWriter out = new PrintWriter(System.out,false);
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNextInt()){

n = scan.nextInt();
m = scan.nextInt();
if( n==0 && m==0)
break;

for(int i=0; i<n; i++) arr[i] = scan.nextInt();
Arrays.sort(arr,0,n);
if(m > n)
m = n;

if(m > 0)
out.print(arr[n-1]);

for(int i=2; i<=m; i++){
out.print(" " + arr[n-i]);
}
out.println();

}
out.flush();
}

}
/**************************************************************
Problem: 1034
User: coder
Language: Java
Result: Accepted
Time:770 ms
Memory:85116 kb
****************************************************************/

cpp 代码如下：

import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

static int arr[] = new int[100001];
static int n,m;

static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNextInt()){

n = scan.nextInt();
m = scan.nextInt();
if( n==0 && m==0)
break;

for(int i=0; i<n; i++) arr[i] = scan.nextInt();
Arrays.sort(arr,0,n);
if(m > n)
m = n;

if(m > 0)
out.print(arr[n-1]);

for(int i=2; i<=m; i++){
out.print(" " + arr[n-i]);
}
out.println();

}
out.flush();
}

}
/**************************************************************
Problem: 1034
User: coder
Language: Java
Result: Accepted
Time:760 ms
Memory:85284 kb
****************************************************************/