var answer = 0
fun main() {
val br = System.`in`.bufferedReader()
val bw = System.out.bufferedWriter()
val n = br.readLine().toInt()
val lines = mutableListOf<Pair<Int, Int>>()
for (i in 0 until n) {
val (x, y) = br.readLine().split(" ").map { it.toInt() }
lines.add(Pair(x, y))
}
lines.sortBy { it.first }
val answer = lineSweepingStartWithOne(lines)
bw.write("$answer")
br.close()
bw.close()
}
fun lineSweepingStartWithOne(lines: MutableList<Pair<Int, Int>>): Int {
var start = lines[0].first
var end = lines[0].second
lines.drop(1).forEach { (x, y) ->
if (isSeparateLine(x, end)) {
accumulateLength(end - start)
// new start position
start = x
end = y
} else if (isLongerLine(y, end)) end = y
}
accumulateLength(end - start)
return answer
}
fun isSeparateLine(x: Int, end: Int): Boolean {
return x > end
}
fun accumulateLength(length: Int) {
answer += length
}
fun isLongerLine(y: Int, end: Int): Boolean {
return y > end
}
O(n)