| Job | Deadline | Profit |
|---|---|---|
| 1 | 2 | 30 |
| 2 | 1 | 35 |
| 3 | 2 | 25 |
| 4 | 1 | 40 |
| Schedule | Profit |
|---|---|
| [1,3] | 30+25 |
| [2,1] | 35+30 |
| [2,3] | 35+25 |
| [3,1] | 25+30 |
| [4,1] | 40+30 |
| [4,3] | 40+25 |
불가능한 경우는 나타내지 않음
마감시간안에 스케쥴링하는 알고리즘을 살펴보기 전에 몇가지를 정의
위의 개념들을 알아보기 위해 deadline이 3까지 있고, 7개의 작업이 있는 경우에 대해 살펴보자
우선 profit이 큰 순서로 내림차순 정렬을 한다.
💡 정렬이 되어있어야 최적의 알고리즘 산출 가능(Profit)
| Job | Deadline | Profit |
|---|---|---|
| 1 | 3 | 40 |
| 2 | 1 | 35 |
| 3 | 1 | 30 |
| 4 | 3 | 25 |
| 5 | 1 | 20 |
| 6 | 3 | 15 |
| 7 | 2 | 10 |
마감시간 있는 스케줄 짜기
void schedule(int n, const int deadline[], sequence_of_integer &J)
{
index i;
sequence_of_integer K;
J = [1];
for (i = 2 ; i <= n ; i++){
K = J에다가 deadline[i]의 값이 작은 것부터 차례로 i를 추가;
if (K가 적절하면) J = K;
}
}
Priority queue 사용 최소힙 허프만 알고리즘 구현
import java.util.*;
//노드 구현
class HuffmanNode implements Comparable<HuffmanNode>{
char key; // 문자
int value; // 빈도수
HuffmanNode left;
HuffmanNode right;
public HuffmanNode(char key, int value){
this.key = key;
this.value = value;
}
@Override
public int compareTo(HuffmanNode o) {
return this.value - o.value;
}
}
public class Huffman {
public static HashMap<Character,String> TransHuffman(String p){
HashMap<Character,Integer> count = new HashMap<>(); // 'a' : 5
// 문자 빈도수 계산
for(char i : p.toCharArray()){
if(!count.containsKey(i)){
count.put(i,1);
}
else{
count.replace(i, count.get(i) + 1);
}
}
// 힙 노드 추가
PriorityQueue<HuffmanNode> huffmanNodes = new PriorityQueue<>();
for(Character key : count.keySet()){
huffmanNodes.offer(new HuffmanNode(key, count.get(key)));
}
// 허프만 트리 생성
while(huffmanNodes.size() > 1){ //전체 노드 수가 2개 이상이면 반복 (하나의 tree로 만들것이기 때문)
HuffmanNode left = huffmanNodes.poll();
HuffmanNode right = huffmanNodes.poll();
HuffmanNode parent = new HuffmanNode('\0', left.value+right.value);
parent.left = left;
parent.right = right;
huffmanNodes.offer(parent);
}
// 허프만 코드 result에 삽입
HashMap<Character,String> result = new HashMap<>(); // 'a' : '001'
if(huffmanNodes.peek().key == '\0'){
GenerateCode(huffmanNodes.peek(), "", result);
}
else{
result.put(huffmanNodes.peek().key, "0");
}
System.out.println(result);
return result;
}
private static void GenerateCode(HuffmanNode node, String code, HashMap<Character,String> codes){ //재귀 호출
if(node == null){
return;
}
if(node.key != '\0'){
codes.put(node.key, code);
}
GenerateCode(node.right, code + "1", codes);
GenerateCode(node.left, code + "0", codes);
}
}