이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
// PUT IT BEFORE THE INCLUDE
#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18 + 7;
template<class T, class Container = vector<T>, class Compare = less<T>>
struct PriorityQueue {
int sz = 0;
priority_queue<T, Container, Compare> pq, del;
void emplace(const T &val) { pq.emplace(val); ++sz; }
void erase(const T &val) { del.emplace(val); --sz; }
void pop() { erase(top()); }
T top() {
while (!del.empty() && !pq.empty() && del.top() == pq.top()) del.pop(), pq.pop();
return pq.top();
}
int size() const {return sz;}
};
template<class T>
struct MedianHeap {
long long sumlo = 0 , sumhi = 0;
PriorityQueue<T> lo;
PriorityQueue<T, vector<T>, greater<T>> hi;
void Fix() {
while (hi.size() > lo.size()){
sumlo += hi.top();
sumhi -= hi.top();
lo.emplace(hi.top());
hi.pop();
}
while (lo.size() > hi.size() + 1){
sumhi += lo.top();
sumlo -= lo.top();
hi.emplace(lo.top());
lo.pop();
}
}
void emplace(const T &val) {
if (lo.size() == 0 || val <= lo.top()){
sumlo += val;
lo.emplace(val);
}
else {
sumhi += val;
hi.emplace(val);
}
Fix();
}
void erase(const T &val) {
if (lo.size() && val <= lo.top()){
sumlo -= val;
lo.erase(val);
}
else {
sumhi -= val;
hi.erase(val);
}
Fix();
}
long long get_ans(){
return (1ll * lo.top() * lo.size() - sumlo) + (sumhi - 1ll * lo.top() * hi.size());
}
T top() { return lo.top(); }
};
bool cmp(array < int , 3 > const& a , array < int , 3 > const& b){
return a[0] < b[0];
}
void solve(){
int k,n;
long long ans0 = 0;
cin >> k >> n;
vector < array < int , 3 > > v2;
for(int i = 0;i<n;i++){
char c1,c2;
int p1,p2;
cin >> c1 >> p1 >> c2 >> p2;
if(c1 == c2){
ans0 += abs(p1 - p2);
}
else{
v2.push_back({p1 + p2 , p1 , p2});
}
}
sort(v2.begin() , v2.end() , cmp);
MedianHeap<int> med1 , med2;
for(auto itr : v2){
med2.emplace(itr[1]);
med2.emplace(itr[2]);
}
long long ans1 = inf;
if(k == 1){
ans1 = med2.get_ans();
}
else{
for(auto itr : v2){
med2.erase(itr[1]);
med2.erase(itr[2]);
med1.emplace(itr[1]);
med1.emplace(itr[2]);
ans1 = min(ans1 , med1.get_ans() + med2.get_ans());
}
}
cout << ans0 + (ans1 == inf ? 0ll : ans1) + v2.size() << '\n';
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int testcase = 1;//cin >> testcase;
while(testcase--)solve();
}
# | 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... |