码迷,mamicode.com
首页 > 其他好文 > 详细

hiho一下 第三十九周(逆序数)

时间:2015-03-31 18:03:28      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:分治   逆序数   

题目连接:点击打开链接


解题思路:

逆序数模板题。注意此题坑点在于数据大,开成unsigned long long


完整代码:

#include <algorithm>
#include <iostream>
#include <cstring>
#include <complex>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
typedef unsigned long long LL;
const int MOD = int(1e9)+7;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const double PI = acos(-1.0); //M_PI;

const int maxn = 2000001;
int n;
LL p[maxn] , t[maxn] , ans;

void merge(int first , int last)
{
    int mid = (first + last) / 2;
    int i1 = 0 , i2 = first , i3 = mid + 1;
    while(i2 <= mid && i3 <= last)
    {
        if(p[i2] > p[i3])
        {
            t[i1 ++] = p[i3 ++];
            ans += mid - i2 + 1;
        }
        else
            t[i1 ++] = p[i2 ++];
    }
    while(i2 <= mid)    t[i1 ++] = p[i2 ++];
    while(i3 <= last)   t[i1 ++] = p[i3 ++];
    i1 = first;
    i2 = 0;
    while(i2 < last - first + 1)
        p[i1 ++] = t[i2 ++];
}

void merge_sort(int first , int last)
{
    if(first < last)
    {
        int mid = (last + first) / 2;
        merge_sort(first , mid);
        merge_sort(mid + 1 , last);
        merge(first , last);
    }
}

int main()
{
    #ifdef DoubleQ
    freopen("in.txt","r",stdin);
    #endif
    while(cin >> n)
    {
        ans = 0;
        memset(p , 0 , sizeof(p));
        memset(t , 0 , sizeof(t));
        for(int i = 0 ; i < n ; i ++)
        {
            cin >> p[i];
        }
        merge_sort(0 , n - 1);
        cout << ans << endl;
    }
    return 0;
}


hiho一下 第三十九周(逆序数)

标签:分治   逆序数   

原文地址:http://blog.csdn.net/u013447865/article/details/44782529

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