1+ /* *
2+ * @file 104396G.cpp
3+ * @author Macesuted (i@macesuted.moe)
4+ * @date 2025-07-24
5+ *
6+ * @copyright Copyright (c) 2025
7+ *
8+ */
9+
10+ #include < bits/stdc++.h>
11+ using namespace std ;
12+
13+ #ifndef LOCAL
14+ #define endl ' \n '
15+ #endif
16+
17+ bool mem1;
18+
19+ using pii = pair<int , int >;
20+
21+ void solve (void ) {
22+ int n;
23+ int64_t C;
24+ cin >> n >> C;
25+
26+ vector<pii> dl, dr;
27+ for (int i = 1 , x, y; i <= n; i++) {
28+ cin >> x >> y;
29+ if (x < y) dr.emplace_back (x, +1 ), dr.emplace_back (y, -1 );
30+ if (x > y) dl.emplace_back (y, +1 ), dl.emplace_back (x, -1 );
31+ }
32+
33+ sort (dl.begin (), dl.end ()), sort (dr.begin (), dr.end ());
34+
35+ vector<pii> rec;
36+ rec.emplace_back (-1e9 - 1 , 0 );
37+ int lv = 0 , rv = 0 ;
38+ for (auto lp = dl.begin (), rp = dr.begin (); lp != dl.end () || rp != dr.end ();) {
39+ int x = min (lp == dl.end () ? INT_MAX : lp->first , rp == dr.end () ? INT_MAX : rp->first );
40+ while (lp != dl.end () && lp->first == x) lv += (lp++)->second ;
41+ while (rp != dr.end () && rp->first == x) rv += (rp++)->second ;
42+ int v = max ({int (lp != dl.end () || rp != dr.end ()), lv, rv});
43+ if (v != rec.back ().second ) rec.emplace_back (x, v);
44+ }
45+
46+ stack<int > S;
47+ S.push (0 );
48+ int64_t ans = 0 ;
49+ for (int i = 1 ; i + 1 < (int )rec.size (); i++) {
50+ int len = rec[i + 1 ].first - rec[i].first ;
51+ ans += (int64_t )len * 2 * rec[i].second + abs (rec[S.top ()].second - rec[i].second ) * C;
52+ while (S.size () > 1 && rec[S.top ()].second < rec[i].second && rec[i].first - rec[S.top ()].first < C) {
53+ auto t = S.top ();
54+ S.pop ();
55+ int delt = min (rec[S.top ()].second , rec[i].second ) - rec[t].second ;
56+ ans -= delt * 2 * (C - (rec[i].first - rec[t].first )), rec[t].second += delt;
57+ if (rec[S.top ()].second > rec[t].second ) S.push (t);
58+ }
59+ if (rec[S.top ()].second < rec[i].second )
60+ while (!S.empty ()) S.pop ();
61+ if (S.empty () || rec[S.top ()].second > rec[i].second ) S.push (i);
62+ }
63+ cout << ans + rec[S.top ()].second * C << endl;
64+
65+ return ;
66+ }
67+
68+ bool mem2;
69+
70+ int main () {
71+ ios::sync_with_stdio (false ), cin.tie (nullptr );
72+ #ifdef LOCAL
73+ cerr << " Memory Cost: " << abs (&mem1 - &mem2) / 1024 . / 1024 . << " MB" << endl;
74+ #endif
75+
76+ int _ = 1 ;
77+ while (_--) solve ();
78+
79+ #ifdef LOCAL
80+ cerr << " Time Cost: " << clock () * 1000 . / CLOCKS_PER_SEC << " MS" << endl;
81+ #endif
82+ return 0 ;
83+ }
0 commit comments