Cpp实现:
#include <cstdio>
#include <queue>
using namespace std;
struct Node
{
int a, b;
Node() {}
Node(int a, int b) : a(a), b(b) {}
bool operator>(const Node& t) const
{
if (a > t.a) return true;
else if (a < t.a) return false;
else b > t.b;
}
bool operator<(const Node& t) const
{
if (a < t.a) return true;
else if (a > t.a) return false;
else return b < t.b;
}
};
priority_queue<Node, vector<Node>, greater<Node>> pq;
//priority_queue<Node> pq;
int main()
{
pq.push(Node(2, 3));
pq.push(Node(2, 2));
pq.push(Node(1, 1));
// pq.push(Node(1, 1));
// pq.push(Node(2, 2));
// pq.push(Node(2, 3));
while (!pq.empty())
{
printf("%d %d\n", pq.top().a, pq.top().b);
pq.pop();
}
return 0;
}
Java实现:
import java.util.*;
public class Main {
// jdk1.8 用lambda: 默认升序排列:o1 < o2 => o1 - o2 < 0,降序排列:o2 - o1
static PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> o1 - o2);
// jdk1.6 用匿名类: 默认升序排列:o1 - o2,降序排列:o2 - o1
static PriorityQueue<Integer> pq1 = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
}
import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main
{
static class Node implements Comparator<Node>
{
int a, b;
public Node() {}
public Node(int a, int b)
{
this.a = a;
this.b = b;
}
@Override
public int compare(Node o1, Node o2)
{
if (o1.a < o2.a) return -1;
else if (o1.a > o2.a) return 1;
else return o1.b - o2.b;
}
// @Override
// public int compare(Node o1, Node o2)
// {
// if (o1.a > o2.a) return -1;
// else if (o1.a < o2.a) return 1;
// else return o2.b - o1.b;
// }
}
static PriorityQueue<Node> pq = new PriorityQueue<>(new Node());
static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException
{
pq.add(new Node(2, 3));
pq.add(new Node(2, 2));
pq.add(new Node(1, 1));
// pq.add(new Node(1, 1));
// pq.add(new Node(2, 2));
// pq.add(new Node(2, 3));
while (!pq.isEmpty())
{
pw.printf("%d %d\n", pq.peek().a, pq.peek().b);
pq.poll();
}
pw.close();
}
}
赞