首页 > 代码库 > hdu-5122-K.Bro Sorting

hdu-5122-K.Bro Sorting

http://acm.hdu.edu.cn/showproblem.php?pid=5122

 

K.Bro Sorting

Time Limit: 2000/2000 MS (Java/Others)    Memory Limit: 512000/512000 K (Java/Others)
Total Submission(s): 228    Accepted Submission(s): 130


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
Hint
In 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亚洲区北京站-重现赛(感谢北师和上交)

 

解题思路:水题

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 int num[1000100];
 7 
 8 int main(){
 9     int t, i, n;
10     int temp, ans;
11     int Case = 1;
12     scanf("%d", &t);
13     while(t--){
14         scanf("%d", &n);
15         for(i = 0; i < n; i++){
16             scanf("%d", &num[i]);
17         }
18         temp = num[n - 1];
19         ans = 0;
20         for(i = n - 1; i >= 0; i--){
21             if(num[i] > temp){
22                 ans++;
23             }
24             temp = min(temp, num[i]);
25         }
26         printf("Case #%d: %d\n", Case++, ans);
27     }
28     return 0;

29 } 

 

hdu-5122-K.Bro Sorting