LRC = $<.map{|ln| ln.split.map(&:to_i) }
N,M = LRC.shift

RC = [[1,0]]
LRC.sort_by{|l,| l }.each{|l,r,c|
	i = RC.bsearch_index{|ir,| l<=ir }
	ic = i ? RC[i][1] : break
	j = ((i...RC.size).bsearch{|j| c+ic<RC[j][1] }||RC.size)
	jr = RC[j-1][0]
	RC.insert(j,[r,c+ic]) if jr < r
}

_,c = RC.pop while RC[-1][0] == N
p(c||-1)
