程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> HDU - 4911 Inversion

HDU - 4911 Inversion

編輯:C++入門知識

HDU - 4911 Inversion



Problem Description bobo has a sequence a1,a2,…,an. He is allowed to swap twoadjacent 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≤ii>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次相鄰的交換的操作,使得序列的逆序數對最小是多少

思路:線段樹和樹狀數組錯了,然後就用歸並排序的方法得到當前序列的逆序數對,然後就是想如果想得到最小的話,那麼我們每次能的是把大的數放到後面,這樣逆序數會減一,然後就能得到答案了

#include 
#include 
#include 
#include 
typedef long long ll;
using namespace std;
const int maxn = 1e5 + 10;

int a[maxn], b[maxn<<1];
int n, k;
ll ans;

void msort(int s, int t) {
	int mid = (s + t) >> 1;
	int qb = 1, bn = t-s+1;
	if (s >= t)
		return;
	msort(s, mid);
	msort(mid+1, t);
	int i, j;
	for (i = s, j = mid+1; i <= mid && j <= t; ) {
		if (a[i] <= a[j]) {
			b[qb] = a[i];
			i++;
		}
		else {
			b[qb] = a[j];
			ans += mid-i+1;
			j++;
		}
		qb++;
	}
	while (i <= mid) 
		b[qb++] = a[i++];
	while (j <= t)
		b[qb++] = a[j++];
	for (i = 1, j = s; i < qb; i++, j++)
		a[j] = b[i];
}

int main() {
	while (scanf("%d%d", &n, &k) != EOF) {
		ans = 0;
		for (int i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		msort(1, n);
		cout << max((ll)0, ans-k) << endl;
	}	
	return 0;
}



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved