From b921ccfe85a225d7c7fda1ea67df705d7cae8784 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Tue, 4 Oct 2022 21:40:39 +0800 Subject: [PATCH] =?UTF-8?q?P3620=20[APIO/CTSC2007]=20=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=A4=87=E4=BB=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/88613869 --- Luogu/P3620/P3620.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Luogu/P3620/P3620.cpp diff --git a/Luogu/P3620/P3620.cpp b/Luogu/P3620/P3620.cpp new file mode 100644 index 00000000..d91d2cdb --- /dev/null +++ b/Luogu/P3620/P3620.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 100005; + +int n, k, a[N], pre[N], suf[N]; +long long c[N], ans; +std::priority_queue< + std::pair, + std::vector>, + auto(*)(std::pair, std::pair)->bool> +q([](std::pair a, std::pair b) -> bool { + return a.second > b.second; +}); + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> k; + + for (int i = 1; i <= n; i++) { + cin >> a[i]; + } + + for (int i = 1; i < n; i++) { + c[i] = static_cast(a[i + 1]) - a[i]; + pre[i] = i - 1; + suf[i] = i + 1; + } + suf[n - 1] = 0; + + for (int i = 1; i < n; i++) { + q.emplace(i, c[i]); + } + + while (k--) { + auto o = q.top(); + q.pop(); + + if (o.second != c[o.first]) { + k++; + + continue; + } + + ans += o.second; + + int l = pre[o.first], + r = suf[o.first]; + + suf[o.first] = suf[r]; + pre[suf[o.first]] = o.first; + pre[o.first] = pre[l]; + suf[pre[o.first]] = o.first; + + c[o.first] = (l && r) ? std::min(static_cast(std::numeric_limits::max()), c[l] + c[r] - c[o.first]) : std::numeric_limits::max(); + c[l] = c[r] = std::numeric_limits::max(); + + q.emplace(o.first, c[o.first]); + } + + cout << ans << endl; + + return 0; +}