树状数组 HDU5775 逆序对

本文探讨了冒泡排序算法的实现及其优化,通过使用树状数组(Binary Indexed Tree)来高效计算每个元素在排序过程中所能达到的最左与最右位置的差值,提供了一种新颖的解题思路。

Bubble Sort

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2442    Accepted Submission(s): 1197

 

Problem Description

P is a permutation of the integers from 1 to N(index starting from 1).
Here is the code of Bubble Sort in C++.


for(int i=1;i<=N;++i)
    for(int j=N,t;j>i;—j)
        if(P[j-1] > P[j])
            t=P[j],P[j]=P[j-1],P[j-1]=t;


After the sort, the array is in increasing order. ?? wants to know the absolute values of difference of rightmost place and leftmost place for every number it reached.

 

Input

The first line of the input gives the number of test cases T; T test cases follow.
Each consists of one line with one integer N, followed by another line with a permutation of the integers from 1 to N, inclusive.

limits
T <= 20
1 <= N <= 100000
N is larger than 10000 in only one case. 

 

Output

For each test case output “Case #x: y1 y2 … yN” (without quotes), where x is the test case number (starting from 1), and yi is the difference of rightmost place and leftmost place of number i.

 

Sample Input

2

3

3 1 2

3

1 2 3

 

Sample Output

Case #1: 1 1 2

Case #2: 0 0 0

 

Hint

In first case, (3, 1, 2) -> (3, 1, 2) -> (1, 3, 2) -> (1, 2, 3) the leftmost place and rightmost place of 1 is 1 and 2, 2 is 2 and 3, 3 is 1 and 3 In second case, the array has already in increasing order. So the answer of every number is 0.

 

题目大意:

有点儿难理解,冒泡排序,每次把从后到当前位遍历,相当于把当前位之后最小的每次都放到当前位,非常有趣。要求,每个数能到达的最右边的位置和最左边的位置之差。

分析:

分析下,每个数其实都是先往右移(最少移0位)再往左移(最少移0位)到位置:那么能到达的最右的位置,就是该数应在的位置加上该数当前位后面比该数小的个数;而能到达的最左的位置,就是当前位和应到位中更小的那一个。

重点理解加粗部分。

也可以反过来想。

(?)

 

代码如下:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define lowbit(x) x&(-x)
using namespace std;

const int maxn=100020;

int n;
int c[maxn],a[maxn];
int ans[maxn];

int sum(int x)
{
	int s=0;
	for(;x;x-=lowbit(x)){
		s+=c[x];
	}
	return s;
}

void add(int x,int y)
{
	for(;x<=n;x+=lowbit(x)){
		c[x]+=y;
	}
}

int main()
{
	int t,cas=0;;

	scanf("%d",&t);
	while(t--){
		memset(c,0,sizeof(c));
		memset(ans,0,sizeof(ans));
		scanf("%d",&n);
		for(int i=1;i<=n;++i){
			scanf("%d",&a[i]);
		}
		for(int i=1;i<=n;++i){
			add(a[i],1);
			ans[a[i]]=a[i]+(i-sum(a[i]))-min(a[i],i);
		printf("Case #%d:",++cas);
		for(int i=1;i<=n;++i)
			printf(" %d",ans[i]);
		printf("\n");
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值