【CodeForces】CF13C Sequence(配数学证明)

题目地址:

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} a1a2...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 1N5000 ) — 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<bibi+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,biA

代码如下:

#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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值