Submission #628133

#TimeUsernameProblemLanguageResultExecution timeMemory
628133kalash04Palembang Bridges (APIO15_bridge)C++17
100 / 100
83 ms6172 KiB
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
#define int long long int
ll MOD = 1e9 + 7;

priority_queue<int, vector<int>, greater<int>> min_heap;
priority_queue<int> max_heap;
int mx, mn;

void insert(int x) {
  int median = (max_heap.size() ? max_heap.top() : 1000000001);
  if(x <= median) {
    max_heap.push(x); 
    mx += x;
  }
  else {
    min_heap.push(x);
    mn += x;
  }
  if(min_heap.size() + 1 < max_heap.size()) {
    int change = max_heap.top();
    mx -= change;
    mn += change;
    max_heap.pop();
    min_heap.push(change);
  } else if(max_heap.size() < min_heap.size()) {
    int change = min_heap.top();
    mn -= change;
    mx += change;
    min_heap.pop();
    max_heap.push(change);
  }
}

void solve() {
  int k, n;
  cin >> k >> n;
  int dist = 0;
  vector<pair<int, int>> v = {{0, 0}};
  for(int i = 0; i < n; i++) {
    char a, b; int c, d;
    cin >> a >> c >> b >> d;
    if(a == b) dist += abs(c - d);
    else v.push_back({c, d});
  }
  sort(v.begin(), v.end(), [](auto const& a, auto const& b) {
    return a.first + a.second < b.first + b.second;
  });
  n = v.size() - 1;
  dist += n;
  mx = mn = 0;
  vector<int> prefix(n + 1);
  for(int i = 1; i <= n; i++) {
    insert(v[i].first);
    insert(v[i].second);
    prefix[i] += mn - mx;
  }
  int ans = prefix[n];
  if(k == 2) {
    while(max_heap.size()) max_heap.pop();
    while(min_heap.size()) min_heap.pop();
    mx = mn = 0;
    for(int i = n; i > 0; i--) {
      insert(v[i].first);
      insert(v[i].second);
      ans = min(ans, prefix[i - 1] + mn - mx);
    }
  }
  cout << dist + ans;
}

int32_t main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
  cout.tie(NULL);
	solve();
}
#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...