Home BOJ. Tell Median Value (1655)
Post
Cancel

BOJ. Tell Median Value (1655)

[Link] https://www.acmicpc.net/problem/1655


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.*;
import java.io.*;

public class Main {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringBuilder sb = new StringBuilder();

    int n = toi(br.readLine());
    PriorityQueue<Integer> minPQ = new PriorityQueue<>();
    PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder());
    boolean odd = true;
    for(int i = 0; i < n; i++) {
      int x = toi(br.readLine());
      if(odd) {
        if(maxPQ.isEmpty()) maxPQ.add(x);
        else {
          int min = minPQ.peek();
          if(x <= min) maxPQ.add(x);
          else {
            maxPQ.add(minPQ.poll());
            minPQ.add(x);
          }
        }
        sb.append(maxPQ.peek() + "\n");
      } else {
        int max = maxPQ.peek();
        if(x >= max) minPQ.add(x);
        else {
          minPQ.add(maxPQ.poll());
          maxPQ.add(x);
        }
        sb.append(Math.min(maxPQ.peek(), minPQ.peek())+ "\n");
      }
      odd = !odd;
    }
    sb.setLength(sb.length() - 1);
    System.out.print(sb);
  }

  public static int toi(String s) { return Integer.parseInt(s); }
}

This post is licensed under CC BY 4.0 by the author.