Bubble Sort
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.
思路:
典型的树状数组求和
首先你要推出我们要的结果就是 abs(min(a[i],i)-(a[i]+c[i])) a[i]是数i的起始位置 c[i]是a[i]右边有多少个比i小的数
可以发现min(a[i],i)为i能达到的最左边的点 (a[i]+c[i]))为i能达到最右边的点举个例子:
4 3 2 1 5
冒泡过程:
4 3 2 1 5
->1 4 3 2 5
-> 1 2 4 3 5
->1 2 3 4 5
以其中的2为例,它所能到达的最左端是他的最终位置(这个数本身代表的位置)和它现在所处位置的最小值,所以2的最左端是2位置,它的最右端是当前初始位置加上它右边比他小的个数,2左边比他小的只有1一个数所以它的最右端位置是4,差值是2
其他同理
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define lowerbit(x) x&(-x)
using namespace std;
const int maxn = 100005;
int N,T;
int a[maxn],p[maxn],c[maxn],sum[maxn];
int add(int x){
while(x <= 100003){
sum[x] += 1;
x += lowerbit(x);
}
}
int getsum(int x){
int ans = 0;
while(x){
ans += sum[x];
x -= lowerbit(x);
}
return ans;
}
int main(){
int cas = 0;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
memset(sum,0,sizeof(sum));
int i;
for(i = 1; i <= N; i++){
scanf("%d",&p[i]);
a[p[i]] = i;//记录p[i]这个数初始位置i
}
for(i = N; i >= 1; i--){//从后往前遍历统计它右边比他小的个数
add(p[i]);
c[p[i]] = getsum(p[i]-1);
}
printf("Case #%d: ",++cas);
for(i = 1; i <= N; i++){
if(i == 1)
printf("%d",abs((a[i]+c[i])-min(a[i],i)));
else
printf(" %d",abs((a[i]+c[i])-min(a[i],i)));
}
printf("\n");
}
return 0;
}