Part 1 定义
建立 的权值数组 ,用线段树维护权值数组来解决问题。在具体的问题中, 数组会有不同的含义。
Part 2 应用
求逆序对
定义:所有满足 的个数。
朴素做法
枚举,时间复杂度 。
优化
的定义:
-
表示 在 中出现的次数。
-
如果 的值代表 在 中出现的次数,那么 在 中的排名为 。
因为维护了排名,所以要对 数组进行离散化。
举个例子:
a 1 2 9 100
a 1 2 3 4其实这两种 数组是等价的,因为他们对应到 数组中的值都是
下标(排名) 1 2 3 4
值 1 1 1 1离散化时注意将 中相同的值对应为一个数。
对于每个 ,要统计答案的话,我们就要向前看,也就是 的个数。对应到数组 中,就是 ,其中 为值域。(因为 数组下标递增,所以 就是 数组中的元素个数。)
为了不让后面的 影响前面的答案,我们的线段树最开始为空,每次计算完答案之后将 。
所以我们就需要一种数据结构,能维护区间求和以及单点修改。
你会说树状数组和线段树都可以。但我只会线段树。
所以我用线段树。总时间复杂度 。
注意离散化不要写错。
AC code
#include <iostream>
#include <algorithm>
#define lc rt << 1
#define rc rt << 1 | 1
using namespace std;
const int N = 5e5 + 10;
typedef long long ll;
ll n, a[N], b[N];
ll st[N << 2], ans;
void pushup(int rt) {st[rt] = st[lc] + st[rc];}
void update(int l, int r, int rt, int x, int k)
{
if (l == r)
{
st[rt] += k;
return;
}
int mid = l + r >> 1;
if (x <= mid) update(l, mid, lc, x, k);
else update(mid + 1, r, rc, x, k);
pushup(rt);
}
ll query(int l, int r, int rt, int x, int y)
{
if (x <= l && r <= y) return st[rt];
ll res = 0, mid = l + r >> 1;
if (x <= mid) res += query(l, mid, lc, x, y);
if (y > mid) res += query(mid + 1, r, rc, x, y);
return res;
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n; i++) b[i] = a[i];
sort(b + 1, b + n + 1);
int m = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; i++)
a[i] = lower_bound(b + 1, b + m + 1, a[i]) - b;
for (int i = 1; i <= n; i++)
{
ans += query(1, m, 1, a[i] + 1, m);
update(1, m, 1, a[i], 1);
}
cout << ans << '\n';
return 0;
}求前驱 / 后继
前驱 / 后继的定义:序列中小于(等于) 的最大的数 / 序列中大于(等于) 的最小的数。
有无等于指的是严格 / 非严格。
对于这道题目,我们显然要找出
的定义: 代表这个数出现过, 代表这个数没有出现过。