【HDU4911】分治求逆序数

来源:互联网 发布:c语言游戏开发教程 编辑:程序博客网 时间:2024/06/06 04:11

Inversion

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 224    Accepted Submission(s): 90


Problem 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 12 2 13 02 2 1
 

Sample Output
12
 

Author
Xiaoxu Guo (ftiasch)
 

Source
2014 Multi-University Training Contest 5
 
#define DeBUG#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>#include <vector>#include <stack>#include <queue>#include <string>#include <set>#include <sstream>#include <map>#include <list>#include <bitset>using namespace std ;#define zero {0}#define INF 0x3f3f3f3f#define EPS 1e-6#define TRUE true#define FALSE falsetypedef long long LL;const double PI = acos(-1.0);//#pragma comment(linker, "/STACK:102400000,102400000")inline int sgn(double x){    return fabs(x) < EPS ? 0 : (x < 0 ? -1 : 1);}#define N 1000005int p[N], t[N];long long anti;//保存逆序数结果int a[N];void merge(int first, int last){    int mid = (first + last) / 2;    int i1 = 0, i2 = first, i3 = mid + 1;    while (i2 <= mid && i3 <= last)    {        if (p[i2] > p[i3])        {            t[i1++] = p[i3++];            anti += mid - i2 + 1;        }        else            t[i1++] = p[i2++];    }    while (i2 <= mid)    {        t[i1++] = p[i2++];    }    while (i3 <= last)    {        t[i1++] = p[i3++];    }    i1 = first;    i2 = 0;    while (i2 < last - first + 1)    {        p[i1++] = t[i2++];    }}void merge_sort(int first, int last){    int mid;    if (first < last)    {        mid = (first + last) / 2;        merge_sort(first, mid);        merge_sort(mid + 1, last);        merge(first, last);    }}int main(){#ifdef DeBUGs    freopen("C:\\Users\\Sky\\Desktop\\1.in", "r", stdin);#endif    int n, k;    while (scanf("%d%d", &n, &k) + 1)    {        anti = 0;        memset(p,0,sizeof(p));        memset(t,0,sizeof(t));        for (int i = 0; i < n; i++)        {            scanf("%d", &p[i]);        }        merge_sort(0, n-1);        if (k > anti)            cout<<0<<endl;        else            cout<<anti-k<<endl;    }    return 0;}


0 0
原创粉丝点击