Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma GCC optimize("03")
- #define _CRT_SECURE_NO_WARNINGS
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cmath>
- #include <iomanip>
- #include <fstream>
- #include <string>
- #include <set>
- #include <deque>
- #include <queue>
- #include <map>
- #include <bitset>
- #include <random>
- #include <cassert>
- #include <unordered_map>
- #include <unordered_set>
- #include <math.h>
- #include <chrono>
- #include <ctime>
- using namespace std;
- using namespace chrono;
- #define all(a) a.begin(), a.end()
- #define allr(a) a.rbegin(), a.rend()
- #define endl "\n"
- mt19937 rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count());
- typedef long long ll;
- typedef long double ld;
- struct Tree {
- const ll inf = 1e18;
- vector<ll> tree;
- map<ll, ll> posit;
- void init(ll n) {
- tree.resize(4 * n, inf);
- }
- void update(ll v, ll tl, ll tr, ll pos, ll add) {
- if (tl == tr) {
- tree[v] = add;
- posit[tl] = v;
- return;
- }
- ll mid = (tl + tr) >> 1;
- if (pos <= mid) {
- update(v << 1, tl, mid, pos, add);
- }
- else {
- update((v << 1) | 1, mid + 1, tr, pos, add);
- }
- tree[v] = min(tree[v << 1], tree[(v << 1) | 1]);
- }
- ll get_min(ll v, ll tl, ll tr, ll l, ll r) {
- if (tr<l || tl>r) {
- return inf;
- }
- if (tl >= l && tr <= r) {
- return tree[v];
- }
- ll mid = (tl + tr) >> 1;
- return min(get_min(v << 1, tl, mid, l, r), get_min((v<<1)|1, mid + 1, tr, l, r));
- }
- void update_el(ll n, ll pos, ll add) {
- update(1, 0, n - 1, pos, add);
- }
- ll qet_mn_seg(ll n, ll l, ll r) {
- return get_min(1, 0, n - 1, l, r);
- }
- };
- signed main() {
- #ifdef _DEBUG
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- srand(time(NULL));
- ll n, m;
- cin >> n >> m;
- vector<pair<ll, ll>> a(m);
- vector<Tree> dp(m);
- for (ll i = 0; i < m; i++) {
- cin >> a[i].first >> a[i].second;
- a[i].first--, a[i].second--;
- dp[i].init(n);
- }
- for (ll i = 0; i < m; i++) {
- for (ll j = 0; j < n; j++) {
- if (i > 0) {
- if (i == 1) {
- cout << "";
- }
- ll len = a[i].second - a[i].first + (ll)1;
- ll len2 = a[i - 1].second - a[i - 1].first + 1;
- if (j - len + 1 < 0) {
- continue;
- }
- ll l = max(len2 - 1, j - len + 1), r = min(n - 1, j + len2 - 1);
- ll cur_min = dp[i - 1].qet_mn_seg(n, l, r);
- dp[i].update_el(n, j, cur_min + abs(a[i].second - j));
- }
- else {
- dp[i].update_el(n, j, abs(a[i].second - j));
- }
- }
- }
- ll ans = dp.back().tree[1];
- cout << ans << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement