H - 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.
感觉又是一道难点主要在读题上的题目。
题意为:求出执行冒泡排序的过程中,数组中的每个数字所能到达的的最左位置与最右位置之间的距离。比方说
[3,1,2]
这个数组中,数字1最靠左时在位置1,最靠右时在位置2,故间距为1;数字2最靠左时在位置2,最靠右时在位置3,故间距为1;数字3最靠左时在位置1,最靠右时在位置3,故间距为2。
由冒泡排序的性质可以知道,对某个数字而言,如果它所在的起始位置编号小于数字本身,如上例中的数字3,它最靠左时的位置就是它的起始位置;而若它所在的起始位置编号大于数字本身,如上例中的数字1,它最靠左时的位置就是它自身数值所述的位置。一个数字能有多靠右,则看数组中这个数字右侧有几个数小于它,如果有n个数小于它,则这个数字最靠右的位置就是它的起始位置右移n位。
有了上述标准,只需求出一个数字右侧小于它的数字的数量,就能结合其起始位置算出答案。这个右侧较小数字的数量通过树状数组得到。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1e5 + 19;
int T, n;
int c[maxn], a, res[maxn];
void add(int x, int d) {
while(x <= n) {
c[x] += d;
x += x & -x;
}
}
int sum(int x) {
int ret = 0;
while(x > 0) {
ret += c[x];
x -= x & -x;
}
return ret;
}
int main() {
#ifdef TEST
freopen("test.txt", "r", stdin);
#endif // TEST
cin >> T;
int cas = 1;
while(T--) {
cin >> n;
memset(c, 0, sizeof(c));
for(int i = 1; i <= n; i++) {
scanf("%d", &a);
res[a] = (a > i ? i : a); // 确定最左位置。
int afterSmaller = a - 1 - sum(a); // 确定最大右移量。
res[a] = abs(res[a] - afterSmaller - i); // 算出最左位置与最右位置的间距。
add(a, 1);
}
printf("Case #%d: ", cas++);
for(int i = 1; i <= n; i++)
printf("%d%c", res[i], " \n"[i == n]);
}
return 0;
}