版本比较
树状数组学习笔记1
正文
增加 13 行删除 13 行
68 行未改动6970717273737475767753 行未改动13113213313413513513613713813929 行未改动16917017117217317317417517617713 行未改动19119219319419519519619719819920020120220320420420520620720820720820921021121221321421121221321421521621721832 行未改动25125225325425525525625725825911 行未改动27127227327427527527627727827964 行未改动68 行未改动 int T = 1; while(T--){ work();} return 0;}``` ```
## 扩展由于树状数组是支持可差分区间查询的数据结构,所以它是可以求出区间最值,逆序对的,接着来看一下吧。
53 行未改动 int T = 1; while(T--){ work();} return 0;}``` ```
# 例题## 逆序对[题目传送门](https://www.luogu.com.cn/problem/P1908)29 行未改动void work(){ cin >> n; for(int i = 1;i <= n;i++){ cin >> a[i]; b[i] = a[i]; b[i] = a[i]; } sort(b + 1,b + 1 + n); m = unique(b + 1,b + 1 + n) - b; for(int i = 1;i <= n;i++){13 行未改动 int T = 1; while(T--){ work();} return 0;}``` ```
## MooFest G[题目传送门](https://www.luogu.com.cn/problem/P2345)
考虑怎么将 $max\{a_i,a_j\} * |x_i - x_j|$ 进行优化,我们很容易想到按 $v$ 排序,这样就能保证当前位置 $i$ 是 $1$ 到 $i - 1$ 的最大值,所以就可以将式子化简。
---
**排序后:** **排序后:**$ans = \sum_{i=1}^n v_i \cdot \sum_{j=1}^{i-1} |x_i - x_j|$
设 $cnt_L$ = 前 $i-1$ 头牛中坐标 $<x_i$ 的个数 $sum_L$ = 它们的坐标和 设 $cnt_L$ = 前 $i-1$ 头牛中坐标 $<x_i$ 的个数$sum_L$ = 它们的坐标和$totalSum$ = 前 $i-1$ 头牛总坐标和
则: $\sum_{j=1}^{i-1} |x_i - x_j|$ $= \sum_{x_j < x_i}(x_i - x_j) + \sum_{x_j > x_i}(x_j - x_i)$ $= (cnt_L \cdot x_i - sum_L) + [(totalSum - sum_L) - (i-1 - cnt_L)\cdot x_i]$ 则:$\sum_{j=1}^{i-1} |x_i - x_j|$$= \sum_{x_j < x_i}(x_i - x_j) + \sum_{x_j > x_i}(x_j - x_i)$$= (cnt_L \cdot x_i - sum_L) + [(totalSum - sum_L) - (i-1 - cnt_L)\cdot x_i]$$= totalSum - (i-1)\cdot x_i + 2\cdot cnt_L \cdot x_i - 2\cdot sum_L$
用树状数组维护 $cnt_L$ 和 $sum_L$ 即可 $O(\log M)$ 计算。
32 行未改动 cin >> a[i].w >> a[i].x; } sort(a + 1,a + 1 + n,[](const node& i,const node& j){ return i.w < j.w; }); }); for(ll i = 1;i <= n;i++){ ll l = sum(a[i].x,0),r = sum(a[i].x,1); ans += (l * a[i].x - r) * a[i].w * 1ll; ans += (abs(r - num) - (i - l - 1) * a[i].x) * a[i].w * 1ll;11 行未改动 ll T = 1; while(T--){ work();} return 0;}``` ```
## LIT-Letters[题目传送门](https://www.luogu.com.cn/problem/P3531)
64 行未改动