https://www.luogu.com.cn/problem/CF13C
题面翻译:
给定一个序列,每次操作可以把某个数加
1
1
1或者减
1
1
1。要求把序列变成非降数列。而且要求修改后的数列只能出现修改前的数。
题目描述:
Little Petya likes to play very much. And most of all he likes to play the following game:
He is given a sequence of N N N integer numbers. At each step it is allowed to increase the value of any number by 1 1 1 or to decrease it by 1 1 1 . The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.
The sequence a a a is called non-decreasing if a 1 ≤ a 2 ≤ . . . ≤ a N a_{1}\le a_{2}\le ...\le a_{N} a1≤a2≤...≤aN holds, where N N N is the length of the sequence.
输入格式:
The first line of the input contains single integer
N
N
N (
1
≤
N
≤
5000
1\le N\le 5000
1≤N≤5000 ) — the length of the initial sequence. The following
N
N
N lines contain one integer each — elements of the sequence. These numbers do not exceed
1
0
9
10^{9}
109 by absolute value.
输出格式:
Output one integer — minimum number of steps required to achieve the goal.
求最小操作次数可以参考https://blog.csdn.net/qq_46105170/article/details/126434434
。这题里要求最后得到的序列只能含修改前的数,所以这里只需要证明存在一个最优解恰好只含修改前的数即可。
设修改前的数集合为
A
A
A,修改后得到的序列为
b
b
b,且操作次数最少,设
a
i
a_i
ai从小到大排好序之后所得的序列为
a
i
′
a'_i
ai′。如果
b
i
∉
A
b_i\notin A
bi∈/A,假设
a
j
′
<
b
i
<
a
j
+
1
′
a'_j
代码如下:
#include
#include
using namespace std;
using LL = long long;
const int N = 5010;
int n, a[N];
LL solve() {
LL res = 0;
priority_queue<int> heap;
for (int i = 1; i <= n; i++) {
heap.push(a[i]);
if (a[i] < heap.top()) {
res += heap.top() - a[i];
heap.pop();
heap.push(a[i]);
}
}
return res;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
printf("%lld\n", solve());
}
时间复杂度 O ( N log N ) O(N\log N) O(NlogN),空间 O ( N ) O(N) O(N)。