浙江工商大学15年校赛I题 Inversion 【归并排序求逆序对】

2023-04-23,,

Inversion
Time Limit
1s
Memory Limit
131072KB
Judge Program
Standard
Ratio(Solve/Submit)
15.00%(3/20)
Description:
bobo has a sequence a1,a2,…,an. He is allowed to swap two adjacent numbers for no more than k times. Find the minimum number of inversions after his swaps. Note: The number of inversions is the number of pair (i,j) where 1≤i<j≤n and ai>aj. Input:
The input consists of several tests. For each tests: The first line contains 2 integers n,k (1≤n≤105,0≤k≤109). The second line contains n integers a1,a2,…,an (0≤ai≤109). Output:
For each tests:
A single integer denotes the minimum number of inversions. Sample Input:
3 1
2 2 1
3 0
2 2 1
Sample Output:
1
2

  

在14年的多校联合训练上写过这道题目

求的是逆序对,数据有10^5大小,用O(n^2)的算法肯定会TLE,那么就自然而然想到了用归并排序(算法导论上也提过这个知识点)

但是这道题需要注意的几点就是,如果ans比交换的次数少那么要输出0,ans可能超出int范围所以需要用long long 类型存储

我们知道,求逆序对最典型的方法就是树状数组,但是还有一种方法就是Merge_sort(),即归并排序。

实际上归并排序的交换次数就是这个数组的逆序对个数,为什么呢?

我们可以这样考虑:

归并排序是将数列a[l,h]分成两半a[l,mid]和a[mid+1,h]分别进行归并排序,然后再将这两半合并起来。

在合并的过程中(设l<=i<=mid,mid+1<=j<=h),当a[i]<=a[j]时,并不产生逆序数;当a[i]>a[j]时,在

前半部分中比a[i]大的数都比a[j]大,将a[j]放在a[i]前面的话,逆序数要加上mid+1-i。因此,可以在归并

排序中的合并过程中计算逆序数.

Source Code:

//#pragma comment(linker, "/STACK:16777216") //for c++ Compiler
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <stack>
#include <string>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <vector>
#include <algorithm>
#define Max(a,b) (((a) > (b)) ? (a) : (b))
#define Min(a,b) (((a) < (b)) ? (a) : (b))
#define Abs(x) (((x) > 0) ? (x) : (-(x)))
#define MOD 1000000007
#define pi acos(-1.0) using namespace std; typedef long long ll ;
typedef unsigned long long ull ;
typedef unsigned int uint ;
typedef unsigned char uchar ; template<class T> inline void checkmin(T &a,T b){if(a>b) a=b;}
template<class T> inline void checkmax(T &a,T b){if(a<b) a=b;} const double eps = 1e- ;
const int N = ;
const int M = * ;
const ll P = 10000000097ll ;
const int MAXN = ;
const int INF = 0x3f3f3f3f ;
const int offset = ; int a[],tmp[];
int n;
ll ans; void Merge (int l,int m,int r) {
int i = l;
int j = m + ;
int k = l;
while (i <= m && j <= r) {
if (a[i] > a[j]) {
tmp[k++] = a[j++];
ans += m - i + ;
} else {
tmp[k++] = a[i++];
}
}
while (i <= m) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
for (int i = l; i <= r; ++i)
a[i] = tmp[i];
} void Merge_sort (int l,int r) {
if (l < r) {
int m = (l + r) >> ;
Merge_sort (l,m);
Merge_sort (m+,r);
Merge (l,m,r);
}
} int main() {
std::ios::sync_with_stdio(false);
int i, j, t, k, u, c, v, p, numCase = ; while (cin >> n >> k) {
for (i = ; i < n; ++i) {
cin >> a[i];
}
ans = ;
Merge_sort(, n - );
if (ans - k < ) {
cout << << endl;
} else {
cout << ans - k << endl;
}
} return ;
}

浙江工商大学15年校赛I题 Inversion 【归并排序求逆序对】的相关教程结束。

《浙江工商大学15年校赛I题 Inversion 【归并排序求逆序对】.doc》

下载本文的Word格式文档,以方便收藏与打印。