TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。
PriorityQueue是从JDK1.5开始提供的新的数据结构接口。
如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。
方法摘要
boolean
add(E e)
将指定的元素插入此优先级队列。
void
clear()
从此优先级队列中移除所有元素。
Comparator<? super E>
comparator()
返回用来对此队列中的元素进行排序的比较器;如果此队列根据其元素的自然顺序进行排序,则返回 null。
boolean
contains(Object o)
如果此队列包含指定的元素,则返回 true。
Iterator<E>
iterator()
返回在此队列中的元素上进行迭代的迭代器。
boolean
ofer(E e)
将指定的元素插入此优先级队列。
E
peek()
获取但不移除此队列的头;如果此队列为空,则返回 null。
E
poll()
获取并移除此队列的头,如果此队列为空,则返回 null。
boolean
remove(Object o)
从此队列中移除指定元素的单个实例(如果存在)。
int
size()
返回此 collection 中的元素数。
Object[]
toArray()
返回一个包含此队列所有元素的数组。
<T> T[]
toArray(T[] a)
返回一个包含此队列所有元素的数组;返回数组的运行时类型是指定数组的类型。
- import java.io.*;
- import java.util.*;
- class Point{
- int x;
- int y;
-
- public Point( int x, int y ){
- this.x = x;
- this.y = y;
- }
- public void print(){
- System.out.println( "" + x + " " + y );
- }
- }
- public class Main{
- public static void main( String [] args )throws Exception{
-
- Scanner cin = new Scanner( System.in );
-
- int n = cin.nextInt();
-
- PriorityQueue queue = new PriorityQueue
-
- ( 1, new Comparator
-
- (){
- public int compare( Point a, Point b ){
- if( a.x < b.x || a.x == b.x && a.y < b.y ){
- return -1;
- }
- else if( a.x == b.x && a.y == b.y ){
- return 0;
- }
- else{
- return 1;
- }
- }
- });
-
- for( int i = 0; i < n; i++ ){
- int x = cin.nextInt();
- int y = cin.nextInt();
-
- Point p = new Point( x, y );
-
- queue.add( p );
- }
-
- while( queue.size() > 0 ){
- Point p = ( Point )queue.poll();
-
- p.print();
- }
- }
- }
-
-
复制代码
源码下载:http://file.javaxxz.com/2014/12/1/000552109.zip |
|