【逆序对】【线段树】【树状数组】Data Structure Special Training 1 T1 rotinv 题解

本文介绍了一种用于解决区间反转查询问题的有效算法。该算法通过预处理数组并使用线段树或树状数组来快速计算任意指定区间内的反转对数量。通过对输入数据进行特定操作,可以在O(log n)的时间复杂度内完成单次查询。

这里写图片描述

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <stack>
#define INF 2100000000
#define LL long long
#define clr(x) memset(x,0,sizeof(x))
#define ms(a,x) memset(x,a,sizeof(x))
#ifdef win32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif

using namespace std;

const int maxx = 1000005;
int n,c[maxx],a[maxx];

template <class T> inline void read(T &x) {
    int flag = 1; x = 0;
    char ch = getchar();
    while(ch <  '0' || ch >  '9') { if(ch == '-')  flag = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') { x = (x<<1)+(x<<3)+ch-'0'; ch = getchar(); }
    x *= flag;
}

inline int lowbit(int x) { return x & (-x); }

inline void add( int x ) { for(register int i = x; i <= n; i += lowbit(i)) c[i] += 1; }

inline int query(int x) {
    int ans = 0;
    for(register int i = x; i; i -= lowbit(i)) ans += c[i];
    return ans;
}

int main() {
    freopen("rotinv.in","r",stdin);
    freopen("rotinv.out","w",stdout);
    scanf("%d",&n);
    LL ans = 0, cnt = 0;
    for(register int i = 1; i <= n; i++) {
        scanf("%d",&a[i]);
        add(a[i]);
        cnt += i-query(a[i]);
    }   
    for(register int i = 1; i <= n; i++) {
        cnt += (n-query(a[i]))-query(a[i]-1);
        ans += cnt;
    }
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值