Sort
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.-
输入
- The input consists of T number of test cases.(<0T<1000) Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n. 输出
- For each case, output the minimum times need to sort it in ascending order on a single line. 样例输入
-
2 3 1 2 3 4 4 3 2 1
样例输出
-
0 6
用冒泡的排序方法把一个序列排成升序,问最少需要多少次交换......
也就是求序列的逆序数,然后双循环果断超时...也就学了归并排序..刚刚学会,还不是太懂,大概说一下自己的想法......
归并排序:
采用递归(分治)的方法进行,也就是和快排有点像,但是处理不一样,归并的策略是,把每一个序列都分成若干个只包含不多于两个元素的小序列,每个序列内部进行排序,然后回溯到上一级,进行不多于四个的小序列的排序.......依次进行下去,平均时间复杂度是 nlog(n)
这个题需要的是在进行排序的时候直接统计逆序对的个数........
#include<stdio.h>
int x[1005],tp[1005],cnt=0,n;
void merge(int l,int mid,int r)
{
int i=l,j=mid+1,k=l;
while(i<=mid&&j<=r)
{
if(x[i]<=x[j])
{
tp[k++]=x[i++];
}
else
{
cnt=cnt+mid-i+1;//为防止重复算,每次只需要统计当前序列的逆序数...
tp[k++]=x[j++];
}
}
while(i<=mid)
{
tp[k++]=x[i++];
}
while(j<=r)
{
tp[k++]=x[j++];
}
for(int i=l;i<=r;++i)
{
x[i]=tp[i];
}
}
void sort(int l,int r)
{
if(l<r)
{
int mid=(l+r)>>1;
sort(l,mid);sort(mid+1,r);//分治
merge(l,mid,r);//合并
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;++i)
{
scanf("%d",x+i);
}
cnt=0;//清零
sort(0,n-1);//调用一次
printf("%d\n",cnt);
}
return 0;
}