题目链接POJ2299

题目大意:给你n个数字,问这段序列类似于冒泡排序后至少需要几次交换。

解题思路:实际上就是求数列的逆序数,树状数组可以解决,由于数据规模大到达long long的规模,离散化一下。注意开的val要为long long!


AC代码

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>

using namespace std;
const int maxn = (int)5e5+5;
typedef long long ll;

ll c[maxn],val[maxn],tmp[maxn],rnk[maxn],n;

template<typename T>
inline int lowbit (T x) {
	return x & (-x);
}

void add (int idx, int num) {
	while (idx <= maxn) {
		c[idx] += num;
		idx += lowbit(idx);
	}
}

int get_sum(int idx) {
	int ans = 0;
	while (idx > 0) {
		ans += c[idx];
		idx -= lowbit(idx);
	}
	return ans;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	while (cin >> n && n) {
		for (int i = 1; i <= n; i++) {
			cin >> val[i];
			tmp[i] = val[i];
		}
		sort(tmp + 1, tmp + n + 1);
		int len = unique(tmp + 1, tmp + 1 + n) - tmp - 1;
		for (int i = 1; i <= n; i++) {
			rnk[i] = lower_bound(tmp + 1, tmp + 1 + len, val[i]) - tmp;
		}
		
		ll res = 0;
		memset(c, 0, sizeof(c));
		for (int i = 1; i <= n; i++) {
			res += i - get_sum(rnk[i]) - 1;
			add(rnk[i],1);
		}
		cout << res << '\n';
	}
	return 0;
}