【SPOJ-INVCNT】Inversion Count【树状数组】【逆序对】

题意:

给出一列数,求逆序对个数。


裸题。

发现树状数组的n与数的个数n搞混了...


懒得离散化,反正时限大。


#include <cstdio>
#include <algorithm>

using namespace std;

typedef unsigned long long ULL;

const int maxn = 200005, maxm = 10000005;

int n, a[maxn], tr[maxm], M;

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int x, int c) {
	for(; x <= M; x += x & -x) tr[x] += c;
}

inline int sum(int x) {
	int res = 0;
	for(; x; x -= x & -x) res += tr[x];
	return res;
}

int main() {
	int T = iread();
	while(T--) {
		n = iread(); M = 0;
		for(int i = 1; i <= n; i++) M = max(M, a[i] = iread());
		for(int i = 1; i <= M; i++) tr[i] = 0;

		ULL ans = 0;
		for(int i = 1; i <= n; i++) {
			ans += i - sum(a[i]) - 1;
			add(a[i], 1);
		}

		printf("%llu\n", ans);
	}
	return 0;
}


你可能感兴趣的:(逆序数,树状数组,逆序对)