Live2D

树状数组求逆序对

逆序对
逆序对就是序列a中ai>aj且i<j的有序对。

 根据上面的定义我们很快的就可以写出O(n^2)的算法,即枚举j,再枚举所有小于j的i,统计ai>aj的数量。但这个算法的时间复杂度过高。
 如果我们能快速的统计出ai>aj的数量,时间复杂度就可以得到很好的提升。
树状数组就可以做到这一点

我们可以先开一个大小为a的最大值的数组t,每当读入一个数时,我们可以用桶排序的思想,将t[a[i]]加上1,然后我们统计t[1]~t[a[i]]的和ans,ans - 1(除掉这个数本身)就是在这个数前面有多少个数比它小。我们只要用i-ans就可以得出前面有多少数比它大,也就是逆序对的数量。

点击查看代码
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> using namespace std; typedef long long ll; const int N = 5e5+5; int n, s[N], m, tmp[N]; ll ans; inline int lb(int x){ return x & -x; } inline void add(int x){ while(x <= N){ tmp[x]++; x += lb(x); } } inline ll gt(int x){ ll sum = 0; while(x){ sum += tmp[x]; x -= lb(x); } return sum; } int main(){ while(~scanf("%d", &n) and n){ for(int i=1; i<=n; i++){ int x; scanf("%d", &x); x++;//防止数据中出现0导致死掉。我们对数据进行加1 add(x); ans += i - gt(x); } printf("%lld\n", ans); } return 0; }

但这样如果数据很大的话空间会过大
比如 1 2 3 4 10 我们要开大小为10的数组存储,可有用的仅是列出的数据,5 6 7 8 9的空间被浪费了

为了解决这个问题,我们可以在读完数数据后对他进行从小到大排序,我们用排完序的数组的下标来进行运算。这样可以保证小的数依旧小,大的数依旧大。这一步叫做离散化

点击查看代码
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> using namespace std; typedef long long ll; const int N = 5e5+5; int n, s[N], m, tmp[N];/*s 离散化数组 tmp 树状数组*/ ll ans; struct tree{ int v, id; bool operator < (const tree &a) const{ return v < a.v; } }t[N]; inline int lb(int x){ return x & -x; } inline void add(int x){ while(x <= n){ tmp[x]++; x += lb(x); } } inline ll gt(int x){ ll sum = 0; while(x){ sum += tmp[x]; x -= lb(x); } return sum; } int main(){ while(~scanf("%d", &n) and n){ ans = 0;//多组数据ans注意赋0 for(int i=1; i<=n; i++){//离散化 scanf("%d", &t[i].v); t[i].v++;//防止数据中出现0导致死掉。我们对数据进行加1 t[i].id = i; } sort(t+1, t+1+n); memset(tmp, 0, sizeof(tmp)); for(int i=1; i<=n; i++){ s[t[i].id] = i; } for(int i=1; i<=n; i++){ add(s[i]); ans += i - gt(s[i]); } printf("%lld\n", ans); } return 0; }

__EOF__

本文作者w1210
本文链接https://www.cnblogs.com/w1210323/p/18020323.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   w1210  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示