CH0304 IncDec Sequence

本文探讨了一种通过区间加减操作使序列统一为单一数值的算法。重点在于如何找到最少的操作次数以及首项可能的取值数量。通过将问题转化为匹配正负数的策略,有效地解决了这一挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意

给定一个序列{ai}\{a_i\}{ai},可以选定一个区间加一或减一,使得{ai}\{a_i\}{ai}为某一个数,问:

  1. 最少的操作次数。
  2. 在1.的条件下a1a_1a1的取值数。

思路

考虑第二问。设差分后序列为{bi}\{b_i\}{bi},区间加减操作可转化为 取两个位置,一加一减,问题可转化为 经过若干操作后,使b2b_2b2bnb_nbn000b1b_1b1的取值方案数
最优解显然是正数和负数匹配作为一次操作,设b2b_2b2bnb_nbn中负数之和的绝对值为s1s1s1,正数之和为s2s2s2,那么第一问就是max{s1,s2}max\{s1,s2\}max{s1,s2}∣s1−s2∣|s1-s2|s1s2b2b_2b2bnb_nbn中匹配完剩余的部分,该部分可以和b1b_1b1bn+1b_{n+1}bn+1匹配,所以第二问易得∣s1−s2∣+1|s1-s2|+1s1s2+1,即b1b_1b1的取值范围是[0,∣s1−s2∣][0,|s1-s2|][0,s1s2]

代码

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;

#define fo(i, x, y) for (int i = x; i <= y; ++i)
#define fd(i, x, y) for (int i = x; i >= y; --i)

const int maxn = 1e5 + 5;

typedef long long ll;

int n;
int a[maxn], b[maxn];

int getint()
{
	char ch;
	int res = 0, p;
	while (!isdigit(ch = getchar()) && (ch ^ '-'));
	p = ch == '-'? ch = getchar(), -1 : 1;
	while (isdigit(ch))
		res = (res << 3) + (res << 1) + (ch ^ 48), ch = getchar();
	return res * p;
}

int main()
{
	n = getint();
	fo(i, 1, n)
	{
		a[i] = getint();
		b[i] = a[i] - a[i - 1];
	}
	ll s1 = 0, s2 = 0;
	fo(i, 2, n)
		if (b[i] < 0) s1 -= b[i];
			else s2 += b[i];
			
	cout << max(s1, s2) << endl;
	cout << abs(s1 - s2) + 1 << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值