이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define int long long
#define fi first
#define se second
using namespace std;
const int inff = 1e18;
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int k, n;
cin >> k >> n;
int ans = 0;
vector<int> a, b;
for (int i = 0; i < n; i++) {
char p, q;
int s, t;
cin >> p >> s >> q >> t;
if (p == q) {
ans += abs(s - t);
} else {
if (s > t) swap(s, t);
a.push_back(s);
b.push_back(t);
}
}
if (k == 1) {
int m = (int)a.size();
vector<int> c;
for (int i = 0; i < m; i++) {
c.push_back(a[i]);
c.push_back(b[i]);
}
sort(c.begin(), c.end());
ans += m;
for (int i = 0; i < 2 * m; i++) {
ans += abs(c[i] - c[m]);
}
cout << ans << '\n';
} else if (k == 2) {
int m = (int)a.size();
vector<pair<int, int>> c;
for (int i = 0; i < m; i++) {
c.push_back({a[i], b[i]});
}
sort(c.begin(), c.end(), [&](pair<int, int> x, pair<int, int> y) {
return x.fi + x.se < y.fi + y.se;
});
int sl = 0, sr = 0;
vector<int> pref(m);
priority_queue<int> le;
priority_queue<int, vector<int>, greater<int>> ri;
for (int i = 0; i < m; i++) {
auto [a, b] = c[i];
sl += a;
le.push(a);
sr += b;
ri.push(b);
while (le.top() > ri.top()) {
int x = le.top(), y = ri.top();
sr += x;
ri.push(x);
sl += y;
le.push(y);
sr -= y;
ri.pop();
sl -= x;
le.pop();
}
pref[i] = ((i + 1) * le.top() - sl) + (sr - (i + 1) * le.top());
}
sl = sr = 0;
while (!le.empty()) le.pop();
while (!ri.empty()) ri.pop();
vector<int> suf(m);
for (int i = m - 1; i >= 0; i--) {
auto [a, b] = c[i];
sl += a;
le.push(a);
sr += b;
ri.push(b);
while (le.top() > ri.top()) {
int x = le.top(), y = ri.top();
sr += x;
ri.push(x);
sl += y;
le.push(y);
sr -= y;
ri.pop();
sl -= x;
le.pop();
}
suf[i] = ((m - i) * le.top() - sl) + (sr - (m - i) * le.top());
}
int mn = inff;
ans += m;
for (int i = 0; i < m - 1; i++) mn = min(mn, pref[i] + suf[i + 1]);
if (m == 0) mn = 0;
ans += mn;
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... |