Submission #316593

#TimeUsernameProblemLanguageResultExecution timeMemory
316593tushar_2658Palembang Bridges (APIO15_bridge)C++14
17 / 100
2094 ms4840 KiB
#include "bits/stdc++.h"
using namespace std;

const int maxn = 200005;
using ll = long long;

map<ll, int> mp;
ll f[maxn];

struct DS {
  vector<ll> v;
  void add(ll x){
    v.push_back(x);
  }
  ll get(){
    sort(v.begin(), v.end());
    int sz = v.size();
    ll mid = f[v[sz / 2]];
    ll ret = 0;
    for(int i = 0; i < sz; ++i){
      ret += llabs(f[v[i]] - mid);
    }
    return ret;
  }
};

int main(int argc, char const *argv[])
{
  ios::sync_with_stdio(false);
  cin.tie(0);

  int k, n;
  cin >> k >> n;
  vector<pair<ll, ll>> v;
  ll ans = 0;
  for(int i = 0; i < n; ++i){
    char c, c1;
    ll x, y;
    cin >> c >> x >> c1 >> y;
    if(c == c1){
      ans += llabs(x - y);
    }else {
      ++ans;
      if(x > y)swap(x, y);
      v.push_back({x, y});
      mp[x];
      mp[y];
    }
  }
  if(v.empty()){
    cout << ans << endl;
    return 0;
  }
  int cnt = 0;
  for(auto& i : mp){
    i.second = ++cnt;
    f[cnt] = i.first;
  }
  n = v.size();
  for(int i = 0; i < n; ++i){
    v[i].first = mp[v[i].first];
    v[i].second = mp[v[i].second];
  }
  sort(v.begin(), v.end(), [&](pair<ll, ll> x, pair<ll, ll> y){
    return x.first + x.second < y.first + y.second;
  });
  DS S, T; 
  vector<ll> pref(n + 1), suff(n + 1);
  for(int i = 0; i < n; ++i){
    S.add(v[i].first);
    S.add(v[i].second);
    pref[i] = S.get();
  }
  for(int i = n - 1; i >= 0; --i){
    T.add(v[i].first);
    T.add(v[i].second);
    suff[i] = T.get();
  }
  ll res = 1e18;
  for(int i = 0; i < n; ++i){
    res = min(res, pref[i] + suff[i + 1]);
  }
  res = min(res, pref[n - 1]);
  if(k == 1){
    printf("%lld\n", pref[n - 1] + ans);
  }else {
    printf("%lld\n", ans + res);
  }

  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...