首页 > 其他 > 详细

MergeAndCount

时间:2021-03-11 17:34:21      阅读:22      评论:0      收藏:0      [点我收藏+]

MergeAndCount_Fighting strength vs Equipment

1.Discription:

If you play games, you will know the importance of your equipment. However, your equipment is not the only thing to determine your success. Therefore, there are a lot of people winning without precious equipment because of their high fighting strength. Now, you are given a fighting strength of each people, (a1, a2, a3,..., an). And the list is sorted according to their equipment value from low to high. Your target is to find how many such pairs (i, j) exists where ai is bigger than aj which means people i with lower equipment but higher fighting strength than people j.

Input

The first line is just an integer n (n is a positive and less than 1000000).

The second line are n integers a1, a2, a3,...,an( abs (ai) is less than 2^31)

Output

You just need to output the number of pairs described above .

Sample Input

5
3 2 1 4 5

Sample Output

3

2.coding

? 实质就是 merge and count。lc 上的 k个逆序对,就是这道题目。

#include<iostream>
using namespace std;
long long int sum = 0;
void merge(long long int arr[], int start, int mid, int end) {
	//复制左右两边的
	long long int *left = new long long int[mid - start + 1];
	for (int i = 0, j = start; i < mid - start + 1; ++i)
		left[i] = arr[j++];

	long long int *right = new long long int[end - mid];
	for (int i = 0, j = mid + 1; i < end - mid; ++i)
		right[i] = arr[j++];

	//合并到 arr 之中去
	int left_index = 0, right_index = 0;
	for (int i = start; i <= end; ++i) {
		if (left_index <= mid - start &&
			(right_index >= end - mid || left[left_index] <= right[right_index]))
			arr[i] = left[left_index++];
		else {
			arr[i] = right[right_index++];
			if (left_index <= mid - start) {
				sum += (mid - start - left_index + 1);
			}
		}//右边的更小,就添加进来
	}
}
void divide(long long int arr[], int start, int end) {
	if (start >= end)
		return;
	else {
		int mid = (start + end) / 2;
		divide(arr, start, mid);
		divide(arr, mid + 1, end);
		//把 start~end 的合起来
		merge(arr, start, mid, end);
	}
}

int main() {
	int n;
	cin >> n;
	long long int *arr = new long long int[n];
	for (int i = 0; i < n; ++i)
		cin >> arr[i];
	divide(arr, 0, n - 1);
	cout << sum << endl;
	system("pause");
	return 0;
}

MergeAndCount

原文:https://www.cnblogs.com/nujer/p/14517670.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!