Inversion HDU - 4911 (逆序对)
bobo has a sequence a 1,a 2,…,a n. 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 a i>a j.
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 a i>a j.
Input
The input consists of several tests. For each tests:
The first line contains 2 integers n,k (1≤n≤10
5,0≤k≤10
9). The second line contains n integers a
1,a
2,…,a
n (0≤a
i≤10
9).OutputFor 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
题意:给你一个序列,任意交换两个相邻元素,不超过k次,在交换之后,问最少的逆序对有多少个?
思路:假设逆序数大于0,存在0 <= i < n使得交换Ai,Ai+1后逆序数降低1,所求答案就为max(ans - k, 0);
利用归并排序计算逆序对数。
#include <iostream> #include <algorithm> #include <string.h> #include <cstdio> #include <string> #include <cmath> #include <vector> #include <stack> #include <queue> #include <stack> #include <list> #include <map> #include <set> //#include <unordered_map> #define Fbo friend bool operator < (node a, node b) #define mem(a, b) memset(a, b, sizeof(a)) #define FOR(a, b, c) for (int a = b; a <= c; a++) #define RFOR(a, b, c) for (int a = b; a >= c; a--) #define off ios::sync_with_stdio(0) #define sc(a) scanf("%d",&a) bool check1(int a) { return (a & (a - 1)) == 0 ? true : false; } using namespace std; typedef pair<int, int> pii; typedef long long ll; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const int Maxn = 2e5 + 9; const double pi = acos(-1.0); const double eps = 1e-8; ll a[Maxn], b[Maxn]; ll ans;//逆序对数量 void msort(ll l, ll r) { if (l == r)return; int mid = (l + r) >> 1; ll i = l, j = mid + 1, k = l; //注意这里i = l k = l (是L而不是1) msort(l, mid), msort(mid + 1, r); while (i <= mid && j <= r) { if (a[i] <= a[j]) b[k++] = a[i++]; else { b[k++] = a[j++]; ans += (mid - i + 1); //记录逆序对数量 } } //一个子序列中的数都处理完了,另一个还没有,把剩下的直接复制过来 while (i <= mid)b[k++] = a[i++]; while (j <= r)b[k++] = a[j++]; for (i = l; i <= r; i++) //把排好序的b[]复制回a[] a[i] = b[i]; } int main() { off; int n, k; while (cin >> n >> k) { ans = 0; FOR(i, 1, n) sc(a[i]); msort(1, n); if (ans <= k)cout << 0 << endl; else cout << ans - k << endl; } }