CF1987B 题解

· · 题解

思路

不管怎么操作,不难得出 \sum k=\sum a_i。所以,我们只要求最少可以取走几个连续线段即可(显然,答案就是所有最长上升子串的最高峰之和)。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int t, n, x, lst, maxx;
ll sum;
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> n >> lst;
        sum = maxx = 0;
        while (-- n) {
            cin >> x;
            if (x < lst)
                maxx = max (maxx, lst - x), sum += lst - x;
            else
                lst = x;
        }
        cout << maxx + sum << '\n';
    }
    return 0;
}