1517: A Sorting Problem
Time Limit: 2 Sec Memory Limit: 32 MBSubmit: 165 Solved: 55
[ Submit][ Status][ Web Board]
Description
There was a boy called ZDD, and he loved a girl who name was SZD. They had led a happy life for a long time. Yesterday, ZDD 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, ZDD comes up with a new algorithm and names it SZD Sorting.
There are many rounds in SZD Sorting. For each round, ZDD 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 2 3 5”, and ZDD chooses “4”, he will get “1 3 2 4 5” after this round. SZD Sorting is similar to Bubble sort, but it’s a randomized algorithm because ZDD will choose a random number at the beginning of each round. ZDD 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, ZDD promises that the elements of the sequence are all different.
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<=109), denoting the sequence ZDD gives you.
Output
For each test case, you should print the answer in one line.
Sample Input
Sample Output
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.
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<cstdio>
using namespace std;
int a[1000001];
int main()
{
int t,n,i,j,temp;
int count1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
count1=0;
memset(a,0,sizeof(a));
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
count1++;//后面的数比前面的数大就表示需要排序
break;
}
}
}
printf("%d\n",count1);
}
return 0;
}