#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "debug.h"
#else
#define dbg(...) 47
#endif
#define int long long
constexpr int inf = 1e18;
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k, n;
cin >> k >> n;
vector<int> pos, l, r;
vector<array<int, 2>> a;
int sum = 0;
for (int i = 0; i < n; i++) {
char p, q;
int s, t;
cin >> p >> s >> q >> t;
if (s > t) swap(s, t);
pos.push_back(s);
pos.push_back(t);
sum += t - s;
if (p != q) {
sum++;
l.push_back(s);
r.push_back(t);
a.push_back({s, t});
}
}
n = a.size();
ranges::sort(l);
ranges::sort(r);
vector<int> p(n + 1), s(n + 1);
for (int i = 0; i < n; i++) {
p[i + 1] = p[i] + r[i];
}
for (int i = n - 1; i >= 0; i--) {
s[i] = s[i + 1] + l[i];
}
ranges::sort(pos);
pos.erase(unique(pos.begin(), pos.end()), pos.end());
int ans = inf;
for (auto x : pos) {
int i = ranges::upper_bound(r, x) - r.begin();
int j = ranges::lower_bound(l, x) - l.begin();
int left = (i * x - p[i]) * 2;
int right = (s[j] - (n - j) * x) * 2;
ans = min(ans, sum + left + right);
}
cout << ans << '\n';
return 0;
}
| # | 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... |