-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
다익스트라 알고리즘 활용
사용된 기능들
| 내용 | 코드 |
|---|---|
| 인접 리스트 | List<Edge>[] adj = new List[N+1]; |
| 최단거리배열 | long[] dist |
| 우선순위 큐 | PriorityQueue<Edge> pq = new PriorityQueue<>(...); |
| 노드/간선 클래스 | class Edge {...} |
PriorityQueue , Compare 비교 연산으로 정렬이 필요하다.
정렬할때 쓰이는 sort 기능에서도 사용가능
비교방법
1. 람다식 + 명시적 변환
Arrays.sort(items, (a, b) -> {
if (a.score < b.score) return -1;
if (a.score > b.score) return 1;
return 0;(a,b) 에서 return 이 음수라면 오름차순 정렬 , 양수라면 내림차순 정렬이다.
활용하여 다음과같이 표현가능 (오버플로우 주의)
1-1.
Arrays.sort(meetings, (m1, m2) -> {
// 종료 시간이 같을 경우 (제2 기준)
if (m1[1] == m2[1]) {
return m1[0] - m2[0]; // 시작 시간 오름차순
}
// 종료 시간이 다를 경우 (제1 기준)
return m1[1] - m2[1]; // 종료 시간 오름차순
});1-2.
PriorityQueue<Integer> pQueue = new PriorityQueue<>((a, b) -> {
int absA = Math.abs(a);
int absB = Math.abs(b);
if (absA != absB) {
// 1순위: 절댓값이 작은 쪽 (absA - absB는 absA가 작을 때 음수를 반환해 우선)
return absA - absB; // 양수면 B우선, 음수면 A 우선
} else {
// 2순위: 절댓값이 같으면 실제 값이 작은 쪽 (a - b는 a가 작을 때 음수를 반환해 우선)
return a - b;
}
});2. 람다식 + Integer.compare() (Long.compare()) 사용
// 오름차순
PriorityQueue pq = new PriorityQueue<>((e1, e2) -> Long.compare(e1.cost, e2.cost));
// 내림차순
PriorityQueue pq = new PriorityQueue<>((e1, e2) -> Long.compare(e2.cost, e1.cost)); // compare의 순서만 변경3. 클래스 자체에 Comparable 구현
class Edge implements Comparable<Edge> {
int to;
long cost;
Edge(int to, long cost) {
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(Edge other) {
if(this.cost < other.cost) return -1;
if(this.cost > other.cost) return 1;
return 0;
// 또는 return Long.compare(this.cost, other.cost);
// 내림차순 return Long.compare(other.cost, this.cost);
}
}Metadata
Metadata
Assignees
Labels
No labels