|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +class Main { |
| 8 | + |
| 9 | + static int bookCnt, bookMax, plusMax, minusMax,ans; |
| 10 | + static PriorityQueue<Integer> plusPq = new PriorityQueue<>(Collections.reverseOrder()); |
| 11 | + static PriorityQueue<Integer> minusPq = new PriorityQueue<>(Collections.reverseOrder()); |
| 12 | + |
| 13 | + public static void main(String[] args) throws NumberFormatException, IOException { |
| 14 | + init(); |
| 15 | + process(); |
| 16 | + print(); |
| 17 | + |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | + public static void init() throws NumberFormatException, IOException { |
| 22 | + BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); |
| 23 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 24 | + |
| 25 | + bookCnt = Integer.parseInt(st.nextToken()); |
| 26 | + bookMax = Integer.parseInt(st.nextToken()); |
| 27 | + plusMax = 0; |
| 28 | + minusMax = 0; |
| 29 | + st = new StringTokenizer(br.readLine()); |
| 30 | + |
| 31 | + for (int i = 0; i < bookCnt; i++) { |
| 32 | + int num = Integer.parseInt(st.nextToken()); |
| 33 | + if (num < 0 ) { |
| 34 | + num *= -1; |
| 35 | + minusPq.add(num); |
| 36 | + minusMax = Math.max(minusMax, num); |
| 37 | + } else { |
| 38 | + plusPq.add(num); |
| 39 | + plusMax = Math.max(plusMax, num); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + public static void process() throws IOException { |
| 46 | + ans = 0; |
| 47 | + |
| 48 | + while (!minusPq.isEmpty()) { |
| 49 | + ans += minusPq.peek(); |
| 50 | + for (int i = 0; i < bookMax; i++) { |
| 51 | + if (minusPq.isEmpty()) break; |
| 52 | + minusPq.poll(); |
| 53 | + } |
| 54 | + |
| 55 | + } |
| 56 | + while (!plusPq.isEmpty()) { |
| 57 | + ans += plusPq.peek(); |
| 58 | + for (int i = 0; i < bookMax; i++) { |
| 59 | + if (plusPq.isEmpty()) break; |
| 60 | + plusPq.poll(); |
| 61 | + } |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + ans *= 2; |
| 66 | + ans -= Math.max(minusMax, plusMax); |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | + public static void print() { |
| 72 | + System.out.println(ans); |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
0 commit comments