C#/알고리즘

백준#1931-회의실배정

McRobbin 2020. 4. 7. 18:00

https://www.acmicpc.net/problem/1931

 

1931번: 회의실배정

(1,4), (5,7), (8,11), (12,14) 를 이용할 수 있다.

www.acmicpc.net

그리디 알고리즘으로 분류된 회의실 배정 문제 입니다.

 

이 문제는

3

4 7

2 5

1 4 와 같이 입력 값의 갯수와 한 쌍의 int가 하나의 데이터로 주어집니다 이를 start, end로 부르겠습니다.

 

이 문제의 핵심은 Sort()입니다. C++, JAVA만 쓰다가 C#으로 만든 객체의 Sort()를 쓰려니 고생을좀 했습니다.

C# Sort()의 방법은 Problem 게시판에 등록 하겠습니다.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _1931
{
    class Job : IComparable
    {
        public int start;
        public int end;
 
        public Job(int start, int end)
        {
            this.start = start;
            this.end = end;
        }
 
        public int CompareTo(Object obj)
        {
            Job other = obj as Job;
            if (this.end == other.end)
                return start.CompareTo(other.start);
            else
                return this.end.CompareTo(other.end);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            int num = int.Parse(Console.ReadLine());
            List<Job> jobList = new List<Job>();
            for (int i = 0; i < num; i++)
            {
                string[] input = Console.ReadLine().Split(' ');
                jobList.Add(new Job(int.Parse(input[0]), int.Parse(input[1])));
            }
 
            jobList.Sort();
 
            int answer = 1;
            Job current = jobList[0];
 
//핵심 부분.
            for (int i = 1; i < jobList.Count; i++)
            {
                if(jobList[i].start >= current.end)
                {
                    current = jobList[i];
                    answer++;
                }
            }
//여기까지.
            Console.WriteLine(answer);
        }
    }
}
 
 
 

우선 두 쌍을 하나로 묶어 List에 저장했습니다. 이를 Sort해야 하는데 기준은

가장 먼저 끝나는 것을 앞으로, 끝나는 시간이 같은 것이 있다면 시작 시간이 먼저인 것을

앞으로 오도록 했습니다. 시작 시간은 이 문제에 관계가 없습니다.

 

Sort가 됐다면 이를 앞에서 부터 보며 진행할 수 있는 회의를 current에 넣고 그렇지 않다면 넘어갑니다.

정렬이 되어 있다면 가장 앞의 회의는 무조건 할 수 있다고 볼 수 있으므로 갯수와 current에 첫번째를

집어넣고 진행하시면 되겠습니다.