Language/Java

Priority Queue 응용

아르비스 2016. 5. 17. 00:41



public class Source2 {

PriorityQueue<Element> pq = new PriorityQueue<Element>();

public static void main(String[] args) {

try {

System.setIn(new FileInputStream("res/input2.txt"));

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Scanner sc = new Scanner(System.in);

PQueue pq = new PQueue();

int size = sc.nextInt();

int num;

System.out.print("set in : ");

for (int i = 0; i < size; i++) {

sc.nextLine();

num = sc.nextInt();

System.out.print(" " + num);

pq.enqueue(num);

}

DeQueue dq = new DeQueue(pq.getQueue());

System.out.println();

System.out.print("Priority Queue : ");

while(!pq.getQueue().isEmpty()) {

System.out.print(" " + pq.dequeue());

}

System.out.println();

System.out.print("Revese Pritory Queue : ");

while(!dq.getQueue().isEmpty()) {

System.out.print(" " + dq.dequeue());

}

}


}


class PQueue {

PriorityQueue<Element> pq = new PriorityQueue<Element>();

public void enqueue(int num) {

pq.add(new Element(num));

}

public PriorityQueue<Element> getQueue() {

return pq;

}

public int dequeue() {

return pq.poll().getNum();

}

}


class DeQueue {

PriorityQueue<Element> dq = new PriorityQueue<Element>(Collections.reverseOrder());

public DeQueue(PriorityQueue<Element> queue) {

dq.addAll(queue);

}

public PriorityQueue<Element> getQueue() {

return dq;

}

public int dequeue() {

return dq.poll().getNum();

}

}


class Element implements Comparable<Element> {

private int num;

public Element(int num) {

this.num = num;

}

public int getNum() {

return num;

}

@Override

public int compareTo(Element o) {

return this.num <= o.num ? -1 : 1;

}

}



input2.txt

10

3

2

1

4

5

6

10

9

8

7



[result]

set in :  3 2 1 4 5 6 10 9 8 7

Priority Queue :  1 2 3 4 5 6 7 8 9 10

Revese Pritory Queue :  10 9 8 7 6 5 4 3 2 1