This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define INF int64_t(1e9)
#define pii pair <int, int>
#define pll pair <long long, long long>
#define mp make_pair
#define file "test"
using namespace std;
const int nmax = 2e5 + 5;
const long long mod = 1e9 + 7;
int n,k;
long long sLow = 0 , sUp = 0, pref[nmax];
long long res = 0;
multiset <int> low, up;
vector <pii> v;
bool cmp(pii a, pii b)
{
return (a.first + a.second < b.first + b.second);
}
void add(int val)
{
int a = (low.size() ? *low.rbegin() : INF+5);
if (val <= a)
{
sLow += val;
low.insert(val);
}
else
{
sUp += val;
up.insert(val);
}
if (up.size() + 1 < low.size())
{
int w = *low.rbegin();
up.insert(w);
low.erase(low.find(w));
sUp += w;
sLow -= w;
}
else if (low.size() < up.size())
{
int w = *up.begin();
low.insert(w);
up.erase(up.find(w));
sUp -= w;
sLow += w;
}
}
void ers(int val)
{
if (up.find(val) != up.end()) up.erase(up.find(val)),sUp-=val;
else low.erase(low.find(val)),sLow-=val;
if (low.empty())
{
low.insert(*up.begin());
sLow+=*up.begin();
sUp-=*up.begin();
up.erase(up.find(*up.begin()));
}
}
int main()
{
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
//freopen(file".inp","r",stdin);
//freopen(file".out","w",stdout);
cin >> k >> n;
v.push_back(mp(0,0));
for (int i=1;i<=n;i++)
{
char a, b;
int x, y;
cin >> a >> x >> b >> y;
if (a == b) res += abs(x-y);
else
{
v.push_back(mp(x,y));
}
}
n = v.size() - 1;
res+=n;
sort(v.begin(), v.end(), cmp);
for (int i=1;i<=n+1;i++)
{
add(v[i].first);
add(v[i].second);
pref[i] = sUp - sLow;
}
long long ans = pref[n];
if (k == 2)
{
up.clear();
low.clear();
sUp = 0;
sLow = 0;
for (int i=n;i;i--)
{
add(v[i].first);
add(v[i].second);
ans = min(ans, sUp - sLow + pref[i-1]);
}
}
cout << ans + res ;
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... |