HDU5122 K. Bro Sorting [tree array], hdu5122k. bro
K. Bro SortingTime Limit: 2000/2000 MS (Java/Others) Memory Limit: 512000/512000 K (Java/Others)
Total Submission (s): 10 Accepted Submission (s): 9
Problem DescriptionMatt's friend K. Bro is an ACMer.
Yesterday, K. bro learned an algorithm: Bubble sort. bubble sort will compare each pair of adjacent items and swap them if they are in the wrong order. the process repeats until no swap is needed.
Today, K. Bro comes up with a new algorithm and names it K. Bro Sorting.
There are supported rounds in K. bro Sorting. for each round, K. bro chooses a number, and keeps swapping it with its next number while the next number is less than it. for example, if the sequence is "1 4 3 2 5", and K. bro chooses "4", he will get "1 3 2 4 5" after this round. k. bro Sorting is similar to Bubble sort, but it's a randomized algorithm because K. bro will choose a random number at the beginning of each round. k. bro wants to know that, for a given sequence, how many rounds are needed to sort this sequence in the best situation. in other words, you shoshould answer the minimal number of rounds needed to sort the sequence into ascending order. to simplify the problem, K. bro promises that the sequence is a permutation of 1, 2 ,..., n.
InputThe first line contains only one integer T (T ≤ 200), which indicates the number of test cases. for each test case, the first line contains an integer N (1 ≤ N ≤ 106 ).
The second line contains N integers ai (1 ≤ ai ≤ N), denoting the sequence K. Bro gives you.
The sum of N in all test cases wocould not exceed 3 × 106.
OutputFor each test case, output a single line "Case # x: y", where x is the case number (starting from 1 ), y is the minimal number of rounds needed to sort the sequence.
Sample Input
255 4 3 2 155 1 2 3 4
Sample Output
Case #1: 4Case #2: 1HintIn the second sample, we choose “5” so that after the first round, sequence becomes “1 2 3 4 5”, and the algorithm completes.
Source2014ACM/ICPC Asia Beijing site-repeat (thanks to beishi and) only needs to calculate the number of numbers on the right side of the competition, which is smaller than it. I forgot how to write the tree array, and finally completed by taojie code.
#include <stdio.h>#include <string.h>#define maxn 1000002int T[maxn], n;int lowBit(int x) { return x & -x; }void add(int v) {for(int pos = v; pos <= n; pos += lowBit(pos))++T[pos];}int getSum(int v) {int sum = 0, i;for(i = v; i > 0; i -= lowBit(i))sum += T[i];return sum;}int main() {int t, i, ans, v;scanf("%d", &t);for(int cas = 1; cas <= t; ++cas) {scanf("%d", &n);memset(T, 0, sizeof(int) * (n + 1));for(i = ans = 0; i < n; ++i) {scanf("%d", &v);add(v);if(getSum(v) != v) ++ans;}printf("Case #%d: %d\n", cas, ans);}return 0;}