CH0304 IncDec Sequence

题意

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

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

思路

考虑第二问。设差分后序列为 { b i } \{b_i\} {bi},区间加减操作可转化为 取两个位置,一加一减,问题可转化为 经过若干操作后,使 b 2 b_2 b2 b n b_n bn 0 0 0 b 1 b_1 b1的取值方案数
最优解显然是正数和负数匹配作为一次操作,设 b 2 b_2 b2 b n b_n bn中负数之和的绝对值为 s 1 s1 s1,正数之和为 s 2 s2 s2,那么第一问就是 m a x { s 1 , s 2 } max\{s1,s2\} max{s1,s2} ∣ s 1 − s 2 ∣ |s1-s2| s1s2 b 2 b_2 b2 b n b_n bn中匹配完剩余的部分,该部分可以和 b 1 b_1 b1 b n + 1 b_{n+1} bn+1匹配,所以第二问易得 ∣ s 1 − s 2 ∣ + 1 |s1-s2|+1 s1s2+1,即 b 1 b_1 b1的取值范围是 [ 0 , ∣ s 1 − s 2 ∣ ] [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、付费专栏及课程。

余额充值