# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1167764 | Nelt | Palembang Bridges (APIO15_bridge) | C++20 | 0 ms | 0 KiB |
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define endl "\n"
using namespace std;
using namespace __gnu_pbds;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
template <typename T, typename key = less<T>>
using ordered_set = tree<T, null_type, key, rb_tree_tag, tree_order_statistics_node_update>;
void solve()
{
ll n, k;
cin >> k >> n;
vector<pair<ll, ll>> a;
vector<ll> l, r;
ll res = 0;
for (ll i = 0; i < n; i++)
{
ll x, y;
char c, d;
cin >> c >> x >> d >> y;
if (c != d) a.push_back(make_pair(min(x, y), max(x, y))), res++;
res += abs(x - y);
}
n = a.size();
for (auto i : a) l.push_back(i.first), r.push_back(i.second);
sort(l.begin(), l.end());
sort(r.begin(), r.end());
if (k == 1)
{
ll ans = 1e18;
ll pref[n], pref1[n];
for (ll i = 0; i < n; i++) pref[i] = (i == 0 ? 0 : pref[i - 1]) + l[i];
for (ll i = 0; i < n; i++) pref1[i] = (i == 0 ? 0 : pref1[i - 1]) + r[i];
for (auto _i : a)
{
for (ll x : {_i.first, _i.second, (_i.first + _i.second) / 2})
{
// ll pos = upper_bound(l.begin(), l.end(), x) - l.begin(), pos1 = upper_bound(r.begin(), r.end(), x) - r.begin();
// ans = min(ans, ((pref[n - 1] - (pos - 1 < 0 ? 0 : pref[pos - 1])) - x * (n - pos) + x * pos1 - (pos1 - 1 < 0 ? 0 : pref[pos1 - 1])) * 2 + res);
ll sum = 0;
for (ll i : l) if (i > x) sum += i - x;
for (ll i : r) if (i < x) sum += x - i;
ans = min(ans, res + sum * 2);
}
}
cout << ans << endl;
}
}