Inversion
题目链接:
http://acm.hust.edu.cn/vjudge/contest/121349#problem/A
Description
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.
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).
Output
For each tests:
A single integer denotes the minimum number of inversions.
3 1
2 2 1
3 0
2 2 1
Sample Output
1
2
##题意:
对有n个元素的数组进行不超过k次操作,每次操作允许交换相邻元素;
求操作后能得到的整个数组的最小逆序数.
##题解:
容易得出每次交换相邻元素最多只能使得逆序数降低1.
而对于一个逆序数不为0的数组,一定存在相邻的两个数满足(i < j, ai < aj)(可反证).
所以每次操作都可以使得逆序数减少1. 最终答案即为max(0, 逆序数).
求逆序数可以用归并排序、树状数组和线段树(数的规模较小时).
##代码:
``` cpp
#include
#include
#include
#include
#include
#include
#include