// #pragma optimize("Ofast")
#include "bits/stdc++.h"
#define int long long
#define FOR(i,x,y) for (int i = x; i < y; i++)
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define em emplace_back
#define mp make_pair
#define F first
#define S second
using namespace std;
template<class C>
using vec = vector<C>;
using vi = vector<int>;
using vpi = vector<pair<int, int> >;
using pii = pair<int, int>;
#ifdef LOCAL
const int N = 15;
#else
const int N = 100001;
#endif
int k, n;
int s[N], t[N];
vi p;
int f(int i, int x) {
return abs(s[i] - x) + abs(t[i] - x);
}
int calc(int x, int y) {
int res = 0;
FOR(i, 0, p.size()) {
res += min(f(p[i], x), f(p[i], y));
}
return res;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> k >> n;
if (k == 2) {
vi pos;
int add = 0;
for (int i = 0, ptr = 0; i < n; i++, ptr++) {
char a, b;
cin >> a >> s[ptr] >> b >> t[ptr];
if (a == b) {
add += abs(s[ptr] - t[ptr]);
ptr--;
continue;
}
add += 1;
pos.pb(s[ptr]);
pos.pb(t[ptr]);
p.pb((int)p.size());
}
sort(all(p), [&](int i, int j) {
return s[i]+t[i] < s[j]+t[j];
});
sort(all(pos));
int ptr = 0;
int ans = LLONG_MAX;
FOR(i, 0, pos.size()) {
while (ptr + 1 < i && calc(pos[ptr], pos[i]) > calc(pos[ptr+1], pos[i])) {
ptr++;
}
ans = min(ans, calc(pos[ptr], pos[i]));
}
if (ans == LLONG_MAX)
ans = 0;
cout << ans + add << '\n';
} else {
assert(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... |