poj2299 Ultra-QuickSort 樹狀數組 + 離散化

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 56422   Accepted: 20845

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 
9 1 0 5 4 ,

Ultra-QuickSort produces the output 
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0


a[i]的數據範圍太大,直接存樹狀數組存不開,要離散化一下。因爲題目中說明了a中每個數字是唯一的,所以可以對a中的數重新賦一個新的較小值,並且不改變他們的相對大小,這樣數據範圍就可以減小到n了,再用樹狀數組求逆序數就行了


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>

using namespace std;

typedef long long ll;

struct node {
	int num, i;
	node() {}
	node(int i, int num) : i(i), num(num) {}
	bool operator < (const node& on) const {
		return this->num < on.num;
	}
}s[500005];

int n, cnt;
int a[500005], BIT[500005];

int lowbit(int x) {
	return x & (-x);
}

void add(int x, int y) {
	for (int i = x; i <= cnt; i += lowbit(i)) {
		BIT[i] += y;
	}
}

int sum(int x) {
	int res = 0;
	for (int i = x; i > 0; i -= lowbit(i)) {
		res += BIT[i];
	}
	return res;
}

int Sum(int l, int r) {
	return sum(r) - sum(l - 1);
}

int main()
{
	while (~scanf("%d", &n) && n) {
		for (int i = 1; i <= n; i++) {
			scanf("%d", &a[i]);
			s[i] = node(i, a[i]);
		}
		sort(s + 1, s + 1 + n);
		cnt = 0;
		for (int i = 1; i <= n; i++) {
			a[s[i].i] = ++cnt;
		}
		ll ans = 0;
		memset(BIT, 0, sizeof(BIT));
		for (int i = 1; i <= n; i++) {
			add(a[i], 1);
			ans += Sum(a[i] + 1, cnt);
		}
		printf("%lld\n", ans);
	}
	return 0;
}


發佈了198 篇原創文章 · 獲贊 8 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章