/* -*- coding: utf-8 -*- * * 2543.cc: No.2543 Many Meetings - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; const int MAX_M = MAX_N * 2; const int BN = 19; const int INF = 1 << 30; /* typedef */ using vi = vector; /* global variables */ int ls[MAX_N], rs[MAX_N], uxs[MAX_M]; vi nbrs[MAX_M]; int dp[MAX_M], ps[MAX_M][BN]; /* subroutines */ /* main */ int main() { int n, k; scanf("%d%d", &n, &k); int m = 0; for (int i = 0; i < n; i++) { scanf("%d%d", ls + i, rs + i); uxs[m++] = ls[i], uxs[m++] = rs[i]; } sort(uxs, uxs + m); m = unique(uxs, uxs + m) - uxs; for (int i = 0; i < n; i++) { int li = lower_bound(uxs, uxs + m, ls[i]) - uxs; int ri = lower_bound(uxs, uxs + m, rs[i]) - uxs; nbrs[li].push_back(ri); } fill(dp, dp + m, -1); dp[0] = 0, ps[0][0] = -1; for (int i = 0; i < m; i++) { if (i + 1 < m) { if (dp[i + 1] < dp[i] || (dp[i + 1] == dp[m] && ps[i + 1][0] < ps[i][0])) dp[i + 1] = dp[i], ps[i + 1][0] = ps[i][0]; } for (auto j: nbrs[i]) { if (dp[j] < dp[i] + 1 || (dp[j] == dp[i] + 1 && ps[j][0] < ps[i][0])) dp[j] = dp[i] + 1, ps[j][0] = i; } } //for (int i = 0; i < m; i++) //printf(" %d,%d,%d", uxs[i], dp[i], ps[i][0]); //putchar('\n'); if (dp[m - 1] < k) { puts("-1"); return 0; } for (int i = 0; i < BN - 1; i++) for (int u = 0; u < m; u++) ps[u][i + 1] = (ps[u][i] >= 0) ? ps[ps[u][i]][i] : -1; int minl = INF; for (int u = m - 1; u >= 0 && dp[u] >= k; u--) { int v = u; for (int i = 0, bi = 1; i < BN; i++, bi <<= 1) if (k & bi) v = ps[v][i]; minl = min(minl, uxs[u] - uxs[v]); } printf("%d\n", minl); return 0; }