HDU 1394 Minimum Inversion Number(线段树求逆序数)

此博客介绍了一个算法问题,即在给定一个整数序列的情况下,通过将其部分元素移动到序列末尾来生成一系列新序列,并计算这些序列的逆序数。目标是找出逆序数最小的序列。通过使用线段树或归并排序等数据结构,可以有效地解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.

For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:

a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)

You are asked to write a program to find the minimum inversion number out of the above sequences.
 

Input

The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
 

Output

For each case, output the minimum inversion number on a single line.
 

Sample Input

10 1 3 6 9 0 8 5 7 4 2
 

Sample Output

16


题意就是输入一个数n,然后输入一个n长度的序列,让你求该序列以及所有变换序列里逆序数最小的一个。

而本题变换序列的逆序数可由公式sum=sum+(n-1-a[i])-a[i]得到,很好证,所以只要求出第一个序列的逆序数,同时记录每个数字a[i]即可。

这道题很水,就算你暴力求逆序数250ms也能过,用线段树或者归并排序要快很多60ms左右。

归并的话适用性更强一些,线段树求逆序数必须这些数字不超过区间长度才行,万一数字是随意的,那么你只能离散化把数字压缩到区间内才能用线段树求解。

还好本题所有数字都在区间n内,妥妥的。

线段树的节点维护该区间的数字数量,每输入一个数进行一次单点更新,同时进行一次区间求和得出比该数字大的数有多少,累加即可得出逆序数之和。


#include<stdio.h>
#include<memory.h>
#define lson l,m,2*rt
#define rson m+1,r,2*rt+1 

const int MAXN=5010;
int num[MAXN*4];
int number[MAXN];

void pushup(int rt)
{
	num[rt]=num[rt*2]+num[rt*2+1];
}

void build(int l,int r,int rt)
{
	if(l==r)
	{
		num[rt]=0;
		return ;
	}
	int m=(l+r)/2;
	build(lson);
	build(rson);
	pushup(rt);
}

void update(int n,int l,int r,int rt)
{
	if(l==r)
	{
		num[rt]=1;
		return;
	}
	int m=(l+r)/2;
	if(n<=m) update(n,lson);
	else update(n,rson);
	pushup(rt);
}

int getnum(int L,int R,int l,int r,int rt)
{
	if(L<=l&&r<=R) return num[rt];
	int m=(l+r)/2;
	int ans=0;
	if(L<=m) ans+=getnum(L,R,lson);
	if(m<R) ans+=getnum(L,R,rson);
	return ans;
}

int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		build(0,n-1,1);
		int suminver=0;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&number[i]);
			update(number[i],0,n-1,1);
			suminver+=getnum(number[i]+1,n-1,0,n-1,1);
		}
		int min=suminver;
		for(int i=0;i<n;i++)
		{
			suminver=suminver+(n-1-number[i])-number[i];
			if(min>suminver) min=suminver;
		}
		printf("%d\n",min);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值