大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

66 lines
1.4 KiB

#include<iostream>
#include<vector>
using namespace std;
const int N=200000;
void merge__(vector<int>& arr, vector<int>& tmp, int l, int mid, int r, int& ret) {
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (arr[i] > arr[j]) {
tmp[k++] = arr[j++];
ret += (mid - i + 1);
}
else {
tmp[k++] = arr[i++];
}
}
while (i <= mid) {
tmp[k++] = arr[i++];
}
while (j <= r) {
tmp[k++] = arr[j++];
}
for (k = 0, i = l; i <= r; ++i, ++k) {
arr[i] = tmp[k];
}
}
void merge_sort__(vector<int>& arr, vector<int>& tmp, int l, int r, int& ret) {
if (l >= r) {
return;
}
int mid = l + ((r - l) >> 1);
merge_sort__(arr, tmp, l, mid, ret);
merge_sort__(arr, tmp, mid + 1, r, ret);
merge__(arr, tmp, l, mid, r, ret);
}
int InversePairs(vector<int>& nums) {
// write code here
int ret = 0;
// 在最外层开辟数组
vector<int> tmp(nums.size());
merge_sort__(nums, tmp, 0, nums.size() - 1, ret);
return ret;
}
int main()
{
vector<int> q;
int n,a;
cin >> n;
int result;
for(int i=0;i<n;i++){
cin >>a;
q.push_back(a);
}
for(int i=0;i<n;i++){
q[i] = -q[i];
result = InversePairs(q);
cout << result<< ' ';
q[i] = -q[i];
}
return 0;
}