hdu 1394 Minimum Inversion Number 线段树 点更新

40 篇文章 0 订阅
14 篇文章 0 订阅
// hdu 1394 Minimum Inversion Number 线段树 点更新
//
// 典型线段树的单点更新
//
// 对于求逆序数,刚开始还真的是很年轻啊,裸的按照冒泡排序
// 求出最初始的逆序数,然后按照公式递推,结果就呵呵了
//
// 发现大牛都是用线段树和树状数组之类的做的,而自己又在学
// 线段树,所以就敲了线段树。
//
// 线段树的节点保存一段区间( L,R )内0,1...n一共出现了多少个。
// 因为每个数是0,1,2...n-1且没有重复的数字。
// 当插入一个数x的时候,我们查询当前状况下(x,n)(ps:本来这段区间内已经
// 有多少个数,将这个结果累加,就是最初的逆序对数。
//
// 之后,就是将开头的数字移动到末尾的情况了
// 首先我们来看一下序列abcde...(每个数都是1到n)到bcde...a逆序数的变化情况
// 设a的值为x,这个序列小于a的值是x-1,大于a的值是n-x。那么
// 将a移动到序列末尾,则小于a的数都变成顺序,大于a的数变成了
// 逆序,那么这个新的逆序数就是 原来的逆序数 + n - a[i] - (a[i] - 1);

// 这题想明白了还是很简单的,继续练,加油

#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define ceil(a,b) (((a)+(b)-1)/(b))
#define endl '\n'
#define gcd __gcd
#define highBit(x) (1ULL<<(63-__builtin_clzll(x)))
#define popCount __builtin_popcountll
typedef long long ll;
using namespace std;
const int MOD = 1000000007;
const long double PI = acos(-1.L);

template<class T> inline T lcm(const T& a, const T& b) { return a/gcd(a, b)*b; }
template<class T> inline T lowBit(const T& x) { return x&-x; }
template<class T> inline T maximize(T& a, const T& b) { return a=a<b?b:a; }
template<class T> inline T minimize(T& a, const T& b) { return a=a<b?a:b; }

const int maxn = 5008 ;

int tree[maxn<<2];

int n;

int a[maxn];

void build(int ro,int L,int R){
	tree[ro] = 0;
	if ( L == R )
		return ;

	int M = L + ( R - L ) / 2;
	build(ro * 2,L,M);
	build(ro * 2 + 1,M+1,R);

}
int p,v;
int ql,qr;
int query(int ro,int L,int R){
	if (ql <= L && R <= qr){
		return tree[ro];
	}
	int M = L + ( R - L ) / 2;
	int ans = 0;
	if (ql <= M)	ans += query(ro * 2,L,M);
	if (M < qr)		ans += query(ro * 2 + 1,M+1,R);
	return ans;
}

void push_up(int ro){
	tree[ro] = tree[ro * 2] + tree[ro * 2 + 1];
}

void update(int ro,int L,int R){
	if ( L == R ){
		tree[ro]++;
		return ;
	}
	int M = L + ( R - L ) / 2;
	if (p<=M)	update(ro * 2,L,M);
	else	update(ro * 2 + 1,M+1,R);
	push_up(ro);
}

void init(){
	build(1,1,n);
	int sum = 0;
	for (int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		p = ++a[i];
		ql = p;
		qr = n;
		sum += query(1,1,n);
		update(1,1,n);
	}

	int res = sum;
	for (int i=1;i<=n;i++){
		sum += n - a[i] - (a[i] - 1);
		res = min(res,sum);
	}

	printf("%d\n",res);
}

int main() {
	//freopen("G:\\Code\\1.txt","r",stdin);
	while(scanf("%d",&n)!=EOF){
		init();

	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值