nyist 129

题目大意:

解决:归并排序


#include <iostream> 
#include <cstdio>
using namespace std;

int num[1000005];
int tmp[1000005];
long long  total;
void merge(int beg,int mid,int end)
{
    int i=beg,j=mid+1,k=0;
    while(i<=mid && j<=end)
    {//最关键的是下边这句话total+= mid-i+1;意思是前边比后边这个数大的个数
        if(num[i]>num[j]){tmp[k++]=num[j++];total+= mid-i+1;}
        else tmp[k++]=num[i++];
    }
    while(i<=mid)tmp[k++]=num[i++];
    while(j<=end)tmp[k++]=num[j++];
    for(i=0,j=beg;i<k;i++)num[j++]=tmp[i];
}
void solve(int beg,int end)
{   
    if(beg<end)
    {
        int mid=(beg+end)/2;
        solve(beg,mid);
        solve(mid+1,end);
        merge(beg,mid,end);
    }
}

int main()
{
    int icase;
    scanf("%d",&icase);
    while(icase--)
    {
        int n;
        total=0;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)scanf("%d",&num[i]);
        solve(1,n);
        printf("%lld\n",total);
    }
    system("pause");
    return 0;
}

posted on 2011-08-17 20:04  猿类的进化史  阅读(203)  评论(0编辑  收藏  举报