K.Bro Sorting
Description
Matt’s friend K.Bro is an ACMer.
Yesterday, K.Bro learnt 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 many 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 should 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 .
Input
The 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 ≤ 10 6).
The second line contains N integers a i (1 ≤ a i ≤ N ), denoting the sequence K.Bro gives you.
The sum of N in all test cases would not exceed 3 × 10 6.
Output
For 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
2
5
5 4 3 2 1
5
5 1 2 3 4
Sample Output
Case #1: 4
Case #2: 1
Hint
In the second sample, we choose “5” so that after the first round, sequence becomes “1 2 3 4 5”, and the algorithm completes.
题意:给你由n个数组成的序列,要把这个序列排序,如果一个数的后面的数有比这个数下,就得移动这个数到达后面的数都大于这个数的位置。问最小的移动数目。
分析:一开始看这个题,以为跟逆序数有关,后来仔细一看,其实没什么关系,就是要我们计算要移动的数的个数而已;这样,我们可以从最后一个数当做最小的数minx,然后往回找,如果遇到比minx大的ans++,遇到比minx小的就更新minx的值,只需要从后往前遍历一次就好了。
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
int a[1000005];
int main ()
{
int t,n;
scanf ("%d",&t);
int cnt=1;
while (t--){
scanf ("%d",&n);
for (int i=0;i<n;i++){
scanf ("%d",&a[i]);
}
int minx=a[n-1];//把最后一个当做minx
int ans=0;
for (int i=n-2;i>=0;i--){
if (a[i]>minx){//与最小值minx比较
ans++;
}
minx=min(a[i],minx);
}
printf ("Case #%d: %d\n",cnt++,ans);
}
return 0;
}