알고리즘 공부/그리디 알고리즘

백준 1931번 with Kotlin

_우지 2021. 8. 7. 12:59

회의실 배정 성공

시간 제한메모리 제한제출정답맞은 사람정답 비율

2 초 128 MB 86500 25717 18527 28.835%

문제

한 개의 회의실이 있는데 이를 사용하고자 하는 N개의 회의에 대하여 회의실 사용표를 만들려고 한다. 각 회의 I에 대해 시작시간과 끝나는 시간이 주어져 있고, 각 회의가 겹치지 않게 하면서 회의실을 사용할 수 있는 회의의 최대 개수를 찾아보자. 단, 회의는 한번 시작하면 중간에 중단될 수 없으며 한 회의가 끝나는 것과 동시에 다음 회의가 시작될 수 있다. 회의의 시작시간과 끝나는 시간이 같을 수도 있다. 이 경우에는 시작하자마자 끝나는 것으로 생각하면 된다.

입력

첫째 줄에 회의의 수 N(1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N+1 줄까지 각 회의의 정보가 주어지는데 이것은 공백을 사이에 두고 회의의 시작시간과 끝나는 시간이 주어진다. 시작 시간과 끝나는 시간은 231-1보다 작거나 같은 자연수 또는 0이다.

출력

첫째 줄에 최대 사용할 수 있는 회의의 최대 개수를 출력한다.

예제 입력 1 복사

11 1 4 3 5 0 6 5 7 3 8 5 9 6 10 8 11 8 12 2 13 12 14

예제 출력 1 복사

4

힌트

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

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
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.Math.pow
import java.lang.NumberFormatException
import java.util.*
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
 
 
val br = BufferedReader(InputStreamReader(System.`in`))
 
fun main()=with(br){
    val bw = BufferedWriter(OutputStreamWriter(System.out))
    val n = readLine()!!.toInt()
    val list = mutableListOf<Pair<Int,Int>>()
    for(i in 0 until n){
        val (a,b) = readLine()!!.split(" ").map{it.toInt()}
        list.add(Pair(a,b))
    }
    list.sortWith(kotlin.Comparator {
            o1, o2 -> o1.first - o2.first
    })
    list.sortWith(kotlin.Comparator {
            o1, o2 -> o1.second - o2.second
    })
    var case1 = Int.MAX_VALUE
    var count = 0
 
    var first = true
 
    //println(list)
    //println(gogo)
    for(i in 0 until list.size){
        //println("list[i].first: ${list[i].first}")
        if(first){
            case1=list[i].second
            //println("i: $i / case1: $case1")
            count++
            first = false
        }
        else if(case1<=list[i].first){
            case1=list[i].second
            //println("i: $i / case1: $case1")
            count++
        }
 
    }
 
 
    //println(count)
    bw.write("$count")
    bw.flush()
    bw.close()
}
 
 
 
 
 
 
 
 
cs