您的位置:首页 > 其它

树状数组-HDU-5775-Bubble Sort

2016-07-28 20:17 337 查看
Bubble Sort

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 122 Accepted Submission(s): 85

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.

Author

FZU

Source

2016 Multi-University Training Contest 4

题意:

给出一个由1~N构成的大小为N的数组,要求在使用冒泡排序把数组排为升序时,每个数最左位置与最右位置之差的绝对值。

题解:

由于排的是升序,则每个数要向左移动的位置只与最终位置以及左边比他大的数的个数有关,那么设原位置为last,左边比他大的数的个数为l,最终位置为f,最左位置为L,那么L=min(last-l,f)。每个数最右边的位置只可能是原位置和最终位置其中之一,那么R=max(last,f)。所以对于每个数的答案就出来了。

对于左边比该数大的数的个数的统计,可以使用树状数组,在输入的同时就进行计算,每次输入一个数x,就对比这个数小的[1,x)区间全部加一,同时查询树状数组中当前x的值,即为当前左边比x大的数的个数。属于区间更新单点求值。

//
//  main.cpp
//  160728-2
//
//  Created by 袁子涵 on 16/7/28.
//  Copyright © 2016年 袁子涵. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
const int MAXN=100005;
long long int n,a[MAXN],tmp;
long long int out[MAXN],l,R,L;
inline long long int LowBit(long long int x)
{
return x&(-x);
}
inline void Add(long long int num,long long int x)
{
while(num>0)
{
a[num]+=x;
num-=LowBit(num);
}
}
inline long long int GetVaule(long long int num)
{
long long int sum=0;
while(num<=n)
{
sum+=a[num];
num+=LowBit(num);
}
return sum;
}
int t;
int main(int argc, const char * argv[]) {
scanf("%d",&t);
int cas=0;
while (t--) {
cas++;
scanf("%lld",&n);
memset(a, 0, sizeof(a));
for (long long int i=1; i<=n; i++) {
scanf("%lld",&tmp);
l=GetVaule(tmp);
L=min(i-l,tmp);
R=max(tmp,i);
out[tmp]=abs(L-R);
Add(tmp-1, 1);
}
printf("Case #%d:",cas);
for (long long int i=1; i<=n; i++) {
printf(" %lld",out[i]);
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: