ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1126. Magnetic Storms

Why TL with n*log(m) solution?
Posted by Vitalii Arbuzov 6 Mar 2011 18:43
Here is my solution. It uses heap(PriorityQueue) and queue(LinkedList). It TLs on 2nd test case. Is there any solution which is asymptotically better than this? What are points to improve?
public class P1126 {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

        in.nextToken();
        int m = (int)in.nval;

        PriorityQueue<Integer> heap = new PriorityQueue<Integer>(m, new Comparator<Integer>() {
            public int compare(Integer i, Integer j) {
                return j.compareTo(i);
            }
        });
        LinkedList<Integer>  queue = new LinkedList<Integer>();
        int cur;
        while (true) {
            in.nextToken();
            cur = (int)in.nval;
            if (cur == -1) break;
            heap.add(cur);
            queue.add(cur);
            if (heap.size() == m) {
                System.out.println(heap.peek());
                heap.remove(queue.pollFirst());
            }
        }
    }
}
Re: Why TL with n*log(m) solution?
Posted by Alipov Vyacheslav [Tomsk PU] 7 Mar 2011 15:27
Your solution's complexity is O(NM), because heap.remove(Object) requires linear time, not O(logN) time.
Re: Why TL with n*log(m) solution?
Posted by vlyubin 16 Apr 2012 00:26
Just submit a brute-force. The easiest improvement is SQRT decomposition, but it's not needed in this case.