标签:des style blog http color strong
| Time Limit: 7000MS | Memory Limit: 65536K | |
| Total Submissions: 39436 | Accepted: 14214 |
Description
In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is
sorted in ascending order. For the input sequence Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
题意:求序列的逆序数。
分析:用归并排序求解。
(具体算法:http://blog.csdn.net/fyxz1314/article/details/37604005)
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define max 510000
#define M 100000000
int a[max];
int L[max],R[max];
__int64 sum;
void merge(int l,int m,int r)
{
int n1,n2;
int i,j,k;
n1=m-l+1; // l 到 m 的元素个数
n2=r-m; // m+1到 r 的元素个数
for(i=1;i<=n1;i++) //把l到m的左边元素复制到L数组里面
L[i]=a[l+i-1];
for(i=1;i<=n2;i++) //把m+1到r的右边元素复制到R数组里面
R[i]=a[m+i];
L[n1+1] = M; // 底部存放“哨兵”,避免比较式判空。 M要比较大。
R[n2+1] = M;
i=1;j=1;
for(k=l;k<=r;k++) // 每次把两堆中最小的元素复制到数组A中,这样合并成有序的序列
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
sum+=(n1-i+1);
}
}
}
void mergesort(int l,int r)
{
int m;
if(l<r)
{
m=(l+r)/2;
mergesort(l,m);
mergesort(m+1,r);
merge(l,m,r);
}
}
int main ()
{
int n,i,j;
while (~scanf("%d",&n)&&n!=0)
{
sum=0;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(0,n-1);
printf("%I64d\n",sum);
}
return 0;
}
poj 2299 Ultra-QuickSort,布布扣,bubuko.com
标签:des style blog http color strong
原文地址:http://blog.csdn.net/fyxz1314/article/details/37603917