题目地址:
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<b_i<a'_{j+1} aj′<bi<aj+1′( b i b_i bi必然在某两个 a ′ a' a′之间的,否则只能让操作次数变得更大),进一步假设 i i i是使得上面不等式成立的最小下标,设 a j ′ < b i ≤ b i + 1 ≤ . . . ≤ b i + c < a j + 1 ′ < b i + c + 1 a'_j<b_i\le b_{i+1}\le ...\le b_{i+c}<a'_{j+1}<b_{i+c+1} aj′<bi≤bi+1≤...≤bi+c<aj+1′<bi+c+1。考虑 a i , a i + 1 , . . . , a i + c a_i,a_{i+1},...,a_{i+c} ai,ai+1,...,ai+c,设这些数大于等于 a j + 1 ′ a'_{j+1} aj+1′的数有 x x x个,小于等于 a j ′ a'_j aj′的数有 y y y个,如果 x > y x>y x>y,那么将 b i , b i + 1 , . . . , b i + c b_i,b_{i+1},...,b_{i+c} bi,bi+1,...,bi+c整体上移可以得到更优解,矛盾;同理如果 x < y x<y x<y也矛盾。当 x = y x=y x=y的时候,可以直接将 b i , b i + 1 , . . . , b i + c b_i,b_{i+1},...,b_{i+c} bi,bi+1,...,bi+c整体下移使得 b i b_i bi移动到 a j ′ a'_j aj′处,仍然是最优解。所以经过有限步就可以使得 ∀ i , b i ∈ A \forall i, b_i\in A ∀i,bi∈A。
代码如下:
#include <iostream>
#include <queue>
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)。