Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2717 寒假作业

P2717 寒假作业

平均值不小于 $k$ ,将所有的数都减去 $k$ ,等价于平均值不小于 $0$ ,即和不小于 $0$ 。

考虑 cdq ,对于 mid 左右两侧,分别求后缀和、前缀和。排序后做双指针,可以做到 $O(n \log ^ 2 n)$ 。

另有加强版 P7868 。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
const int N = 1e5 + 10;
int n, m, w[N], tmp[N];
LL cdq(int l, int r)
{
if (l == r)
return w[l] >= 0;
int mid = l + r >> 1;
LL res = cdq(l, mid) + cdq(mid + 1, r);
tmp[mid] = w[mid], tmp[mid + 1] = w[mid + 1];
for (int i = mid - 1; i >= l; i--)
tmp[i] = tmp[i + 1] + w[i];
for (int i = mid + 2; i <= r; i++)
tmp[i] = tmp[i - 1] + w[i];
sort(tmp + l, tmp + mid + 1);
sort(tmp + mid + 1, tmp + r + 1);
for (int i = l, j = r; i <= mid; i++)
{
while (j > mid && tmp[i] + tmp[j] >= 0)
j--;
res += r - j;
}
return res;
}
int main()
{
read(n), read(m);
for (int i = 1; i <= n; i++)
read(w[i]), w[i] -= m;
write(cdq(1, n));
return 0;
}