java优先队列

优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。

PriorityQueue是从JDK1.5开始提供的新的数据结构接口。
    如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。 

方法摘要
booleanadd(E e) 
将指定的元素插入此优先级队列。
voidclear() 
从此优先级队列中移除所有元素。
Comparator<? super E>comparator() 
返回用来对此队列中的元素进行排序的比较器;如果此队列根据其元素的自然顺序进行排序,则返回 null。
booleancontains(Object o) 
如果此队列包含指定的元素,则返回 true。
Iterator<E>iterator() 
返回在此队列中的元素上进行迭代的迭代器。
booleanofer(E e) 
将指定的元素插入此优先级队列。
Epeek() 
获取但不移除此队列的头;如果此队列为空,则返回 null。
Epoll() 
获取并移除此队列的头,如果此队列为空,则返回 null。
booleanremove(Object o) 
从此队列中移除指定元素的单个实例(如果存在)。
intsize() 
返回此 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();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值