JAVA优先队列总结

可以自定义比较器排序

以题目为例:http://www.51nod.com/Challenge/Problem.html#!#problemId=1163

package aCM;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;

class nodess {
	int v;
	int time;

	public nodess(int v, int time) {
		super();
		this.v = v;
		this.time = time;
	}

	public nodess() {
		super();
		// TODO Auto-generated constructor stub
	}

}

public class Main15 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		int n, s;
		n = cin.nextInt();
		List list = new LinkedList();
		for (int i = 1; i <= n; i++) {
			int v, time;
			time = cin.nextInt();
			v = cin.nextInt();
			nodess no = new nodess(v, time);
			list.add(no);
		}
		list.sort(new Comparator() {
			@Override
			public int compare(nodess o1, nodess o2) {
				// TODO Auto-generated method stub
				return o1.time-o2.time;//时间从小到大排列
			}
		});
		Comparatorcom=new Comparator() {

			@Override
			public int compare(Integer o1, Integer o2) {
				// TODO Auto-generated method stub
				return o1-o2;
			}
		};
		PriorityQueueque=new PriorityQueue(com);//默认从小到大,队列头部小;
		long sum = 0;
		int t=0;
		for (nodess l : list) {//看时间!
			if(l.time>que.size())
			{
				sum+=l.v;
				que.add(l.v);
				//这个时候直接进去
			}else
			{
				//如果这个点的时间比较早
				sum+=l.v;
				que.add(l.v);
				sum-=que.poll();//先加进去,反正后面小点是v要出去。
			}
		}
		System.out.println(sum);
	}

}

 

你可能感兴趣的:(JAVA)