终极火箭


私信TA

用户名:computerboy

访问量:651

签 名:

等  级
排  名 11267
经  验 980
参赛次数 0
文章发表 1
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:

本题主要是通过改用排序算法,将比较标准改成两个数之间绝对值之间的比较,如此就可以得到按照绝对值的大小排序的一个序列;然后从已排序的序列中从按次序取m个数累乘。在累乘之前应该先计算在m个数的范围内,有几个数是负数,如果数量为偶数,则可以直接完成对m个数的累乘;如果数量为奇数,则可以除去最后一个负数,再乘上m个数后的第一个正数。


注意事项:

不知道为什么最后会告诉我是ArrayIndexOutOfBoundsException,求大佬指教。

参考代码:

import java.util.*;
public class Main{
 public static void main(String[] args){
  Scanner sc = new Scanner(System.in);
  int count,n,m;
  int res = 1;
  count = sc.nextInt();
  int cnt_N = 0;
  while(count-- > 0) {
   n = sc.nextInt();
   m = sc.nextInt();
   int[] a = new int[n];  
   for(int i = 0;i < a.length;i++) {
    a[i] = sc.nextInt();
   }
   sort(a);
   int rem = -1,k = -1;
   for(int i = 0;i < m;i++) {
    if(a[i] < 0) {
     rem = i;
     cnt_N++;
    }
   }
   if(cnt_N % 2 == 0) {
    for(int i = 0;i < m;i++) {
     res *= a[i];
    }
   }else {
    for(int i = 0;i < m;i++) {
     res *= a[i];
    }
    for(int i = m;i < a.length;i++) {
     if(a[i] > 0) {
      k = i;
      break;
     }
    }
    res = res / a[rem] * a[k];
   }
   System.out.println(res);
  }
 }
 public static void sort(int[] a) {
  for(int i = 0;i < a.length;i++) {
   for(int j = i + 1;j < a.length;j++) {
    if(Math.abs(a[i]) < Math.abs(a[j])) {
     int t = a[i];
     a[i] = a[j];
     a[j] = t;
    }
   }
  }
 }
}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区