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;
}
posted @ 2024-02-19 08:40  w1210  阅读(30)  评论(0编辑  收藏  举报