이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using ll = long long;
using std::vector;
template <class T>
constexpr T inf = std::numeric_limits<T>::max() / 2;
class slope_trick {
std::priority_queue<int> left;
std::priority_queue<int, vector<int>, std::greater<>> right;
ll min;
public:
slope_trick() : left(), right(), min(0) {}
void add(const int x) {
if (!left.empty() and x < left.top()) {
min += left.top() - x;
left.push(x);
right.push(left.top());
left.pop();
} else {
right.push(x);
}
if (!right.empty() and x > right.top()) {
min += x - right.top();
right.push(x);
left.push(right.top());
right.pop();
} else {
left.push(x);
}
}
ll minimum() const {
return min;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int K, N;
std::cin >> K >> N;
vector<int> S, T;
ll must = 0;
while (N--) {
char p, q;
int a, b;
std::cin >> p >> a >> q >> b;
if (p == q) {
must += std::abs(a - b);
} else {
must += 1;
S.push_back(a);
T.push_back(b);
}
}
N = (int)S.size();
vector<int> ord(N);
std::iota(ord.begin(), ord.end(), 0);
std::sort(ord.begin(), ord.end(), [&](const int i, const int j) {
return S[i] + T[i] < S[j] + T[j];
});
vector<ll> pref(N + 1), suff(N + 1);
slope_trick slope;
for (int i = 0; i < N; ++i) {
const int k = ord[i];
slope.add(S[k]);
slope.add(T[k]);
pref[i + 1] = slope.minimum();
}
slope = slope_trick();
for (int i = N - 1; i >= 0; --i) {
const int k = ord[i];
slope.add(S[k]);
slope.add(T[k]);
suff[i] = slope.minimum();
}
if (K == 1) {
std::cout << must + pref[N] << '\n';
} else {
ll min = inf<ll>;
for (int i = 0; i <= N; ++i) {
min = std::min(min, pref[i] + suff[i]);
}
std::cout << must + min << '\n';
}
}
# | 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... |