/*K.Bro Sorting Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 512000/512000 K (Java/Others) Total Submission(s): 188 Accepted Submission(s): 106 Problem 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 ≤ 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 would not exceed 3 × 106. 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 HintIn the second sample, we choose “5” so that after the ?rst round, sequence becomes “1 2 3 4 5”, and the algorithm completes. Source 2014ACM/ICPC亚洲区北京站-重现赛(感谢北师和上交) Recommend liuyiding | We have carefully selected several similar problems for you: 5126 5125 5124 5123 5122 */ #include<stdio.h> int a[1000010]; int main() { int T, i, j, n, ans, cas = 1; scanf("%d", &T); while(T--) { scanf("%d", &n); ans = 0; for(i = 0; i < n; i++) scanf("%d", &a[i]); j = a[n-1]; for(i = n-2; i >= 0; i--)//逆序判断序列中的每个数的右边是否存在比当前数小的数 { if(a[i] > j) ans++; else j = a[i]; } printf("Case #%d: %d\n", cas++, ans); } return 0; }
题意 :给出一个序列,每一次可以从数列中任意的一个数开始向右移动,直到遇到比它大的数。求一个数列最少需要移动多少次才能使序列呈升序排列。
思路:此题的关键在于能够推出规律,即查看序列上的每一位数的右边是否有比它更小的数,若有则次数加一。至于这个规律,自己慢慢体会吧。