HZOJ-248:逆序对个数

题目描述

​ 输入 N 组数据,对每组数据输出逆序对个数。


输入

​ 对于每组测试用例,第一行输入此组数据元素个数 x�,接下来 x� 行,每行一个数,表示元素。(1≤x≤500000)(1≤�≤500000)

​ 当读入的元素个数 x� 为零时,程序结束。

输出

​ 对于每组测试用例,输出一个数,表示逆序对个数。


样例输入
5
9
1
0
5
4
3
1
2
3
0
样例输出
6
0

数据规模与约定

​ 时间限制:1 s

​ 内存限制:256 M

​ 100% 的数据保证 1≤x≤500000

2023.9.15

#include 
#include 
int arr[500005], temp[500005];
long long merge_sort(int* arr, int l, int r) {
    if (r - l <= 1) return 0;
    int mid = (r + l) / 2;
    long long  a = merge_sort(arr, l, mid);
    long long  b = merge_sort(arr, mid, r);
    long long c = 0;
    int p1 = l, p2 = mid, k = 0;
    while (p1 < mid || p2 < r) {
        if (p2 == r || (p1 < mid && arr[p1] <= arr[p2])) {
            temp[k++] = arr[p1++];
        }
        else {
            temp[k++] = arr[p2++];
            c += (mid - p1);
        }
    }
    for (int i = l; i < r; i++) {
        arr[i] = temp[i - l];
    }
    return a + b + c;
}

void solve(int n) {
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
    printf("%lld\n", merge_sort(arr, 0, n));
    return;
}

int main() {
    int n;
    while(1){
        scanf("%d", &n);
        if (n != 0) solve(n);
        else break;
    }
    return 0;
}

2023.10.6

#include 
#include 

long long ans[500000] = { 0 };
void merge(int* arr, int l, int r, long long* n) {
	if (r - l < 2) return;
	int mid = (l + r) / 2;
	merge(arr, l, mid, n);
	merge(arr, mid, r, n);
	int* temp = (int*)malloc(sizeof(int) * (r - l));
	int p1 = l, p2 = mid, k = 0;
	while (p1 < mid || p2 < r) {
		if (p2 == r || (p1 < mid && arr[p1] <= arr[p2])) {
			temp[k++] = arr[p1++];
		}
		else temp[k++] = arr[p2++], *n += (mid - p1);
	}
	for (int i = l; i < r; i++) arr[i] = temp[i - l];
	free(temp);
	return;
}

int main() {
	int c = 0;
	do {
		int n;
		scanf("%d", &n);
		if (n == 0) break;
		int* arr = (int*)malloc(sizeof(int) * n);
		for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
		merge(arr, 0, n, &ans[c]);
		c++;
	} while (1);
	for (int i = 0; i < c; i++) printf("%lld\n", ans[i]);
	return 0;
}

你可能感兴趣的:(算法题,算法)