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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
|
using System;
using System.Collections.Generic;
public class Solution
{
public int[] solution(string[] operations)
{
int[] answer = { 0, 0 };
PriorityQueue<int> priorityQueue = new PriorityQueue<int>();
foreach (string operation in operations)
{
string[] split = operation.Split(' ');
if (split[0] == "I")
priorityQueue.Enqueue(int.Parse(split[1]));
if (split[0] == "D")
{
if (priorityQueue.Count == 0)
continue;
int number = int.Parse(split[1]);
if (number > 0)
{
priorityQueue.RemoveMaxValue();
}
else
{
priorityQueue.Dequeue();
}
}
}
if (priorityQueue.Count == 0)
{
return answer;
}
else if (priorityQueue.Count == 1)
{
int number = priorityQueue.Dequeue();
return new int[] { number, number };
}
else
{
return new int[] { priorityQueue.RemoveMaxValue(), priorityQueue.Dequeue() };
}
}
}
// 기본 값은 최소 우선순위 큐
public class PriorityQueue<T>
{
// 힙 조건 : 부모노드는 항상 자식노드보다 우선순위가 낮아야한다.
private readonly List<T> heap;
private readonly IComparer<T> comparer;
public PriorityQueue() : this(Comparer<T>.Default) { }
public PriorityQueue(IComparer<T> comparerValue)
{
heap = new List<T>();
comparer = comparerValue;
}
public int Count => heap.Count;
//맨 끝에 추가하고 힙 조건을 다시 체크
public void Enqueue(T item)
{
// 맨 끝에 추가
heap.Add(item);
int index = Count - 1;
// 힙 조건을 확인할 때까지 계속 돈다.
while (index > 0)
{
//방금 추가한 노드의 부모 노드
int parentIndex = (index - 1) / 2;
//부모 노드의 우선순위가 방금 추가한 노드보다 낮다면 힙조건이 만족한 것.
if (comparer.Compare(heap[index], heap[parentIndex]) >= 0)
break;
//부모 노드가 더 우선순위가 더 높다면 서로 바꾼다.
Swap(index, parentIndex);
//이제 바꾼 노드의 자식노드를 다시 검사한다.
index = parentIndex;
}
}
// 가장 낮은 우선순위를 가진 노드(맨 위에 있는 노드)을 반환하고 힙 조건을 다시 체크
public T Dequeue()
{
// 힙의 루트에 있는 항목이 가장 낮은 우선순위를 가진다.
// 최종 return되는 값은 이 값이지만, 힙 조건을 만족하는지 검사를 해야한다.
T item = heap[0];
// 힙의 마지막 노드를 맨 위로 이동시킨다.
heap[0] = heap[Count - 1];
heap.RemoveAt(Count - 1);
int index = 0;
// 힙 조건을 확인할 때까지 계속 돈다.
while (true)
{
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
// 모든 자식 노드를 확인한 경우 종료.
if (leftChildIndex >= Count)
break;
// 두 자식 노드 중 우선순위가 낮은 노드를 선택한다.
int minChildIndex = (rightChildIndex < Count //오른쪽 노드가 있는지 부터 검사.. 없다면 leftChildIndex를 반환한다.
&& comparer.Compare(heap[rightChildIndex], heap[leftChildIndex]) < 0) ? //둘 중 더 낮은 우선순위를 가진 노드를 뽑아야 한다.
rightChildIndex : leftChildIndex;
// 위 조건에서 뽑은 노드와 현재 노드를 비교한다.
// 뽑은 노드가 현재 노드보다 우선순위가 높다면, 힙 조건을 만족하는 것이니 안바꿔도 되고, 그만체크해도 된다.
if (comparer.Compare(heap[index], heap[minChildIndex]) <= 0)
break;
// 뽑은 노드가 현재 노드보다 우선순위가 낮다면, 현재 노드와 뽑은 노드를 바꿔줌으로서 힙 조건을 만족하게 한다.
Swap(index, minChildIndex);
// 이제 뽑았던 노드의 자식 노드를 다시 검사한다.
index = minChildIndex;
}
return item;
}
private void Swap(int indexA, int indexB)
{
T temp = heap[indexA];
heap[indexA] = heap[indexB];
heap[indexB] = temp;
}
public T RemoveMaxValue()
{
int maxIndex = 0;
for (int i = 1; i < Count; i++)
{
if (comparer.Compare(heap[i], heap[maxIndex]) > 0)
{
maxIndex = i;
}
}
T maxValue = heap[maxIndex];
heap.RemoveAt(maxIndex);
return maxValue;
}
}
|
cs |
기존에 구현했었던 PriortyQueue에 RemoveMaxValue()를 추가해서 풀었다.
처음에는 우선순위 큐의 마지막 인덱스가 최대값일거라고 생각했는데, 첫노드가 가장 우선순위가 낮은건 맞지만,
힙 조건이 만족한다고 해서 마지막 인덱스가 항상 최대 우선순위는 아니라는 것을 알게되었다.
'프로그래머스 - 내 풀이 > 프로그래머스 Lv3' 카테고리의 다른 글
[C#]프로그래머스/N으로 표현/DP (0) | 2023.04.29 |
---|---|
[C#]프로그래머스/네트워크/그래프,DFS (2) | 2023.04.28 |
[C#]프로그래머스/가장 먼 노드/BFS,그래프 (0) | 2023.04.27 |
[C#]프로그래머스/입국심사/이진탐색 (0) | 2023.04.25 |
[C#]프로그래머스/단어변환/DFS (0) | 2023.04.24 |