樹狀陣列-HDU-5775-Bubble Sort
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;
}