반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 성적평가
- 연결요소
- 6987
- 물채우기
- msSQL
- 백준
- 처우산정
- incr
- 파라메트릭
- upper_bound
- 경력
- 소프티어
- @P0
- 매개변수탐색
- BOJ
- 백트래킹
- 처우협의
- dfs
- 이분탐색
- 퇴사통보
- 오퍼레터
- OFFSET
- boj #19237 #어른 상어
- BFS
- 기술면접
- compose
- 13908
- softeer
- Docker
- Kafka
Archives
- Today
- Total
기술 블로그
우선순위 큐(PriorityQueue) compareTo 본문
728x90
반응형
JAVA에서는 C++에 있는 pair 개념이 없어서 직접 구현해줘야 하고, 정렬(?) 방식도 구현해줘야 한다.
아래 2가지 구조(골격)를 기억하자.
1.
class Pair implements Comparable<Pair> {
}
2.
public int compareTo(Pair p) {
}
1 2 3 4 5 6 7 8 9 10 11 | -1, -2 -1, -2 1, 2 1, 3 2, 3 3, 42 4, 4 5, -4 6, 4 12, 3 | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | import java.io.*; import java.util.*; public class Main { static int n; static PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); /*n = Integer.parseInt(br.readLine()); for(int i=0; i<n; i++) { }*/ pq.add(new Pair(1, 2)); pq.add(new Pair(4, 4)); pq.add(new Pair(2, 3)); pq.add(new Pair(1, 3)); pq.add(new Pair(-1, -2)); pq.add(new Pair(3, 42)); pq.add(new Pair(5, -4)); pq.add(new Pair(12, 3)); pq.add(new Pair(6, 4)); pq.add(new Pair(-1, -2)); while(!pq.isEmpty()) { System.out.println(pq.peek().first + ", " + pq.peek().second); pq.remove(); } /*bw.flush(); bw.close();*/ } } class Pair implements Comparable<Pair> { int first, second; Pair(int f, int s) { this.first = f; this.second = s; } public int compareTo(Pair p) { if(this.first < p.first) { return -1; // 오름차순 } else if(this.first == p.first) { if(this.second < p.second) { return -1; } } return 1; // 이미 this.first가 더 큰 것이 됐으므로, 1로 해준다. -1로 // -1로 하면 결과가 이상하게 출력됨. } } | cs |
728x90
반응형
'JAVA' 카테고리의 다른 글
직렬화(Serialization)와 역직렬화(Deserialization), transient 변수 (0) | 2023.09.07 |
---|---|
어노테이션(Annotation) (0) | 2020.06.07 |
자바 가상 기계, JVM(Java Virtual Machine) (0) | 2020.01.29 |
Java vector sort (0) | 2020.01.08 |