2014 Multi-University Training Contest 5 HDOJ 4911 Inversion

題目:

Inversion

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


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 1 2 2 1 3 0 2 2 1
 

Sample Output
1 2

解題思路:

求出序列的逆序數,減去k即爲所求結果。這裏用O(n2)的算法會超時,我們只能用O(nlogn)的算法,可以用樹狀數組離散化求解,也可以用歸併排序求解,ps:逆序數可能會超int範圍。


代碼:

#include<iostream>
#include<fstream>
using namespace std;
const int N=500005;
int a[N];
int t[N];
long long sum;
void copy(int *dest,int *src,int b,int e)
{
	while(b<=e)
	{
		dest[b]=src[b];
		b++;
	}
}

void merge(int * a,int b,int m, int e)
{
	int i=b;
	int j=m+1;
	int k=b;
	while((i<=m)&&(j<=e))
	{
		if(a[i]<=a[j])
			t[k++]=a[i++];

		else
		{
			t[k++]=a[j++];
			sum+=(m-i+1);
		}
	}
	while(i<=m)
	{
		t[k++]=a[i++];
	}
	while(j<=e)
	{
		t[k++]=a[j++];
	}
	copy(a,t,b,e);
}

void mergesort(int * a,int i,int j)
{
		if(i>=j)return;
		int m=(i+j)/2;
		mergesort(a,i,m);
		mergesort(a,m+1,j);
		merge(a,i,m,j);
}

int main()
{
	int n, k;
	std::ios::sync_with_stdio(false);
	while(cin>>n>>k)
	{
		sum=0;
		for(int i=0;i<n;i++)
			cin>>a[i];
		mergesort(a,0,n-1);
		sum -= k;
		if(sum < 0) sum = 0;
		cout<< sum <<endl;
	}
	return 0;
}


發佈了187 篇原創文章 · 獲贊 14 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章