码迷,mamicode.com
首页 > 编程语言 > 详细

1203: 逆序数 ( 归并排序 )

时间:2015-04-13 09:40:33      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

1203: 逆序数
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 125 Solved: 26
[Submit][Status][Web Board]
Description

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数不小于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input

多组测试数据

每组测试数据分两行,第一行一个正整数n(n <= 50000)

第二行有n个元素( 0 <= A[i] <= 10^9)

Output

每组测试数据输出一行表示逆序数

Sample Input
4
2 4 3 1
3
1 1 1
Sample Output
4

3

//注意题目中的红色的部分,对应代码修改红色的地方,一般情况下是<=的关系

#include<cstdio>
#include<algorithm>
//#include<bits/stdc++.h>
using namespace std;
template<class T>inline T read(T&x)
{
    char c;
    while((c=getchar())<=32)if(c==EOF)return 0;
    bool ok=false;
    if(c=='-')ok=true,c=getchar();
    for(x=0; c>32; c=getchar())
        x=x*10+c-'0';
    if(ok)x=-x;
    return 1;
}
template<class T> inline T read_(T&x,T&y)
{
    return read(x)&&read(y);
}
template<class T> inline T read__(T&x,T&y,T&z)
{
    return read(x)&&read(y)&&read(z);
}
template<class T> inline void write(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x<10)putchar(x+'0');
    else write(x/10),putchar(x%10+'0');
}
template<class T>inline void writeln(T x)
{
    write(x);
    putchar('\n');
}
//-------ZCC IO template------
const int maxn=50011;
const double inf=999999999;
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define For(i,t,n) for(int i=(t);i<(n);i++)
typedef long long  LL;
typedef double DB;
typedef pair<int,int> P;
#define bug printf("---\n");
#define mod 10007

int ans=0;
void merge_sort(int *A,int x,int y,int *T)
{
    if(y-x>1)
    {
        int p=x,m=(x+y)/2;
        int i=x;
        int q=m;
        merge_sort(A,x,m,T);
        merge_sort(A,m,y,T);
        while(p<m||q<y)
        {
            if(q>=y||(p<m&&<span style="color:#FF0000;">A[p]<A[q]</span>))T[i++]=A[p++];
            else {T[i++]=A[q++];ans+=m-p;}
        }
        for(int i=x;i<y;i++)
            A[i]=T[i];
    }
}
 int a[maxn];
 int b[maxn];
int main()
{
    #ifndef ONLINE_JUDGE
   // freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int n,m,i,j,k,t;
    while(read(n))
    {
        For(i,0,n)
        {
            read(a[i]);
        }
        ans=0;
        merge_sort(a,0,n,b);
        writeln(ans);
    }
    return 0;
}















1203: 逆序数 ( 归并排序 )

标签:

原文地址:http://blog.csdn.net/u013167299/article/details/45014017

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!