码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4911 Inversion(归并求逆序对)

时间:2014-08-05 22:36:10      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   for   ar   代码   

HDU 4911 Inversion

题目链接

题意:给定一个数组,可以相邻交换最多k次,问交换后,逆序对为多少

思路:先利用归并排序求出逆序对,然后再减去k就是答案

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int N = 100005;
int n, num[N], save[N], sn;

void init() {
    for (int i = 0; i < n; i++)
	scanf("%d", &num[i]);
}

long long solve(int l, int r, int *num) {
    if (r - l < 1) return 0;
    int mid = (l + r) / 2;
    long long ans = solve(l, mid, num) + solve(mid + 1, r, num);
    sn = l;
    int ll = l, rr = mid + 1;
    while (ll <= mid && rr <= r) {
	if (num[ll] <= num[rr])
	    save[sn++] = num[ll++];
	else {
	    ans += (mid + 1 - ll);
	    save[sn++] = num[rr++];
	}
    }
    while (ll <= mid) save[sn++] = num[ll++];
    while (rr <= r) save[sn++] = num[rr++];
    for (int i = l; i <= r; i++)
	num[i] = save[i];
    return ans;
}

long long k;

int main() {
    while (~scanf("%d%I64d", &n, &k)) {
	init();
	long long ans = solve(0, n - 1, num);
	ans = max(ans - k, 0LL);
	printf("%I64d\n", ans);
    }
    return 0;
}


HDU 4911 Inversion(归并求逆序对),布布扣,bubuko.com

HDU 4911 Inversion(归并求逆序对)

标签:style   http   color   os   io   for   ar   代码   

原文地址:http://blog.csdn.net/accelerator_/article/details/38391161

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!