#include <bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define len(s) (ll) s.size()
#define pb push_back
#define F first
#define S second
using namespace std;
typedef long long ll;
const int N = 6e5 + 17;
const int P = 31;
const int mod = 1e9 + 7;
const ll inf = 1e18;
ll n, m, sz, res;
ll l[N], r[N], ord[N], was[N], d[N], mx[N], val[N];
map < ll, ll > id;
vector < pair < ll, ll > > vec;
vector < pair < ll, ll > > g[N];
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m, res = inf;
for(ll i = 1; i <= n; i++){
cin >> l[i] >> r[i], ord[i] = i;
if(r[i] < l[i]) r[i] = r[i] + m;
vec.pb({l[i], r[i]});
vec.pb({r[i], inf});
vec.pb({l[i] + m - 1, inf});
}
sort(all(vec));
for(ll i = 0; i < len(vec); i++){
if(!id[vec[i].F]) id[vec[i].F] = ++sz, val[sz] = vec[i].F;
if(vec[i].S != inf) mx[id[vec[i].F]] = max(mx[id[vec[i].F]], vec[i].S);
}
for(ll i = 1; i <= sz; i++){
if(mx[i]) g[i].pb({id[mx[i]], 1});
if(i > 1) g[i].pb({i - 1, 0});
}
for(ll i = 1; i <= sz; i++){
if(!mx[i]) continue;
set < pair < ll, ll > > q;
for(ll j = 1; j <= sz; j++) d[j] = inf;
d[i] = 0, q.insert({d[i], i});
while(len(q)){
ll v = (q.begin() -> S); q.erase(q.begin());
for(auto [u, w] : g[v])
if(d[v] + w < d[u])
q.erase({d[u], u}), d[u] = d[v] + w, q.insert({d[u], u});
}
for(ll j = 1; j <= sz; j++)
if(val[i] + m - 1 <= val[j])
res = min(res, d[j]);
}
if(res == inf) res = -1;
cout << res;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |