题意
给定一个序列 { a i } \{a_i\} {ai},可以选定一个区间加一或减一,使得 { a i } \{a_i\} {ai}为某一个数,问:
- 最少的操作次数。
- 在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|
∣s1−s2∣为
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
∣s1−s2∣+1,即
b
1
b_1
b1的取值范围是
[
0
,
∣
s
1
−
s
2
∣
]
[0,|s1-s2|]
[0,∣s1−s2∣]。
代码
#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;
}