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
|
using System;
using System.Collections.Generic;
public class Solution
{
public PriorityQueue<Job> jobPriorityQueue = new PriorityQueue<Job>();
public struct Job : IComparable<Job>
{
public int startTime;
public int taskTime;
// 구조체 생성자
public Job(int startTimeValue, int taskTimeValue) : this()
{
this.startTime = startTimeValue;
this.taskTime = taskTimeValue;
}
// 작업 간 비교를 위한 CompareTo 메소드
public int CompareTo(Job other)
{
return taskTime.CompareTo(other.taskTime);
}
}
public int solution(int[,] jobs)
{
int n = jobs.GetLength(0);
List<Job> tempList = new List<Job>(jobs.GetLength(0));
// 작업 목록 초기화
for (int i = 0; i < n; i++)
tempList.Add(new Job(jobs[i, 0], jobs[i, 1]));
// 작업 시작 시간 기준으로 정렬
tempList.Sort((a, b) => a.startTime.CompareTo(b.startTime));
Queue<Job> jobQueue = new Queue<Job>(tempList);
// 현재 시간 및 대기 시간 초기화
int currentTime = 0;
int totalWaitingTime = 0;
// 작업 목록과 우선순위 큐에 작업이 남아있는 동안 실행
while (jobQueue.Count > 0 || jobPriorityQueue.Count > 0)
{
// 작업 목록에서 요청 시간이 현재 시간보다 같거나 작은 것들을 우선순위 큐에 넣는다.
// 현재 시간에서 처리 가능한 작업들을 넣는 것.
while (jobQueue.Count > 0 && jobQueue.Peek().startTime <= currentTime)
jobPriorityQueue.Enqueue(jobQueue.Dequeue());
// 우선순위 큐에서 작업을 꺼내고 처리
if (jobPriorityQueue.Count > 0)
{
//가장 요청시간이 짧은 작업이 꺼내진다.
Job currentJob = jobPriorityQueue.Dequeue();
//현재 시간에 꺼낸 작업의 소요시간을 더한다.
currentTime += currentJob.taskTime;
//이 작업의 대기시간 = 현재시간 - 요청 시간
int waitingTime = currentTime - currentJob.startTime;
//총 대기시간에 더해준다.
totalWaitingTime += waitingTime;
}
// 작업 목록에만 작업이 남아있으면 현재 시간에 처리 가능한 작업이 없다는 것. 시간을 더해준다.
else if (jobQueue.Count > 0)
{
currentTime++;
}
}
// 평균 대기시간을 반환한다. (소수점 버림)
return totalWaitingTime / n;
}
}
|
cs |
우선순위 큐 (PrioirtyQueue) 는 따로 구현하여 사용했다.
https://enum01.tistory.com/148
'프로그래머스 - 내 풀이 > 프로그래머스 Lv3' 카테고리의 다른 글
[C#]프로그래머스/네트워크/그래프,DFS (2) | 2023.04.28 |
---|---|
[C#]프로그래머스/이중우선순위큐 (0) | 2023.04.28 |
[C#]프로그래머스/가장 먼 노드/BFS,그래프 (0) | 2023.04.27 |
[C#]프로그래머스/입국심사/이진탐색 (0) | 2023.04.25 |
[C#]프로그래머스/단어변환/DFS (0) | 2023.04.24 |