Submission #1291025

#TimeUsernameProblemLanguageResultExecution timeMemory
1291025minhphanPalembang Bridges (APIO15_bridge)C++17
100 / 100
200 ms11400 KiB
#include <bits/stdc++.h>

using namespace std;

//Die kürzeste Distanz von einer Person, die in der gleichen Zone lebt
//und zur Arbeit geht, kann sich durch den Brückenbau nicht ändern.

multiset<int> low, high;
long long lowSum, highSum;

void insert(int x) {
    if (low.empty() || x <= *low.rbegin()) {
        low.insert(x);
        lowSum += x;
    } else {
        high.insert(x);
        highSum += x;
    }

    if (low.size() > high.size() + 1) {
        highSum += *low.rbegin();
        lowSum -= *prev(low.end());

        high.insert(*low.rbegin());
        low.erase(prev(low.end()));
    } else if (high.size() > low.size()) {
        lowSum += *high.begin();
        highSum -= *high.begin();

        low.insert(*high.begin());
        high.erase(high.begin());
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    low.clear();
    high.clear();
    lowSum = 0;
    highSum = 0;

    int K, N;
    cin >> K >> N;

    long long sameZone = 0;
    vector<pair<int, int>> citizens; //S T
    citizens.emplace_back(0, 0);

    for (int i = 0; i<N; i++) {
        char p, q;
        int s, t;
        cin >> p >> s >> q >> t;
        if (p == q) {
            sameZone += abs(s-t);
        } else {
            citizens.emplace_back(s, t);
        }
    }

    sort(citizens.begin(), citizens.end(), [&](const pair<int, int> &p1, const pair<int, int> &p2) {
        return p1.first + p1.second < p2.first + p2.second;
    });

    int n = citizens.size()-1;
    sameZone += n;

    vector<long long> prefix(n+1);

    for (int i = 1; i<=n; i++) {
        insert(citizens[i].first);
        insert(citizens[i].second);

        prefix[i] = highSum-lowSum;
    }

    long long answer = prefix[n];

    if (K == 2) {
        low.clear();
        high.clear();
        lowSum = 0;
        highSum = 0;

        for (int i = n; i>=1; i--) {
            insert(citizens[i].first);
            insert(citizens[i].second);
            answer = min(answer, highSum - lowSum + prefix[i - 1]);
        }
    }

    cout << sameZone + answer;
}
#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...