前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POJ-2299 Ultra-QuickSort(用树状数组求逆序对数)

POJ-2299 Ultra-QuickSort(用树状数组求逆序对数)

作者头像
_DIY
发布2020-02-24 15:30:49
3350
发布2020-02-24 15:30:49
举报

ac代码

代码语言:javascript
复制
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define mp make_pair
#define pi acos(-1)
#define pii pair<int, int>
#define pll pair<long long , long long>
#define ll long long
#define ld long double
#define MEMS(x) memset(x, -1, sizeof(x))
#define MEM(x) memset(x, 0, sizeof(x))
const int inf = 0x3f3f3f3f;
const int maxn = 500001;
using namespace std;
int n;
struct Intg
{
    int data;
    int pos;
    bool operator<(const Intg num) const
    {
        return data < num.data;
    }
}a[maxn];
int p[maxn], d[maxn];
int lowbit(int x)
{
    return x & (-x);
}
void update(int x)
{
    while(x <= maxn)
    {
        d[x]++;
        x += lowbit(x);
    }
}
int getsum(int x)
{
    int ans = 0;
    while(x)    //一定写成这种形式,否则写成for循环形式会导致超时
    {
        ans += d[x];
        x -= lowbit(x);
    }
    return ans;
}
int main()
{
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    while(scanf("%d", &n) != EOF && n)
    {
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i].data);
            a[i].pos = i;
        }
        sort(a + 1, a + n + 1);
        p[a[1].pos] = 1;
        int idx = 1;
        for(int i = 2; i <= n ; i++)
        {
            if(a[i].data == a[i-1].data)
                p[a[i].pos] = idx;
            else
                p[a[i].pos] = ++idx;
        }
        ll ans = 0;
        memset(d, 0, sizeof(d));
        for(int i = 1; i <= n; i++)
        {
            update(p[i]);
            ans += i - getsum(p[i]);
        }
        printf("%lld\n", ans);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档