#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll one_bridge_cost(const vector<pair<ll,ll>>& segs) {
vector<ll> pts;
pts.reserve(segs.size() * 2);
for (auto &p : segs) {
pts.push_back(p.first);
pts.push_back(p.second);
}
sort(pts.begin(), pts.end());
ll x = pts[pts.size() / 2];
ll cost = 0;
for (auto &p : segs) {
cost += llabs(p.first - x) + llabs(p.second - x) + 1;
}
return cost;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int K, N;
cin >> K >> N;
ll answer = 0;
vector<pair<ll,ll>> cross;
for (int i = 0; i < N; i++) {
char P, Q;
ll S, T;
cin >> P >> S >> Q >> T;
if (P == Q) {
answer += llabs(S - T);
} else {
ll L = min(S, T);
ll R = max(S, T);
cross.push_back({L, R});
}
}
if (cross.empty()) {
cout << answer << "\n";
return 0;
}
if (K == 1) {
answer += one_bridge_cost(cross);
cout << answer << "\n";
return 0;
}
int M = cross.size();
sort(cross.begin(), cross.end(), [](auto &a, auto &b){
return (a.first + a.second) < (b.first + b.second);
});
vector<ll> pref(M), suff(M);
for (int i = 0; i < M; i++) {
vector<pair<ll,ll>> tmp(cross.begin(), cross.begin() + i + 1);
pref[i] = one_bridge_cost(tmp);
}
for (int i = M - 1; i >= 0; i--) {
vector<pair<ll,ll>> tmp(cross.begin() + i, cross.end());
suff[i] = one_bridge_cost(tmp);
}
ll best = LLONG_MAX;
for (int i = 0; i + 1 < M; i++) {
best = min(best, pref[i] + suff[i + 1]);
}
answer += best;
cout << answer << "\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... |