1. 程式人生 > >求逆序對

求逆序對

spl ans stream oid close algo ostream nbsp span

方法一:樹狀數組

模板如下:

技術分享
#include<iostream>
#include<cstdio>
#include <algorithm>
using namespace std;
const int MAXN=40001;
int n, a[MAXN], tree[MAXN], tot;

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


int query(int x) {
    int ans=0;
    while (x>0) {
        ans+=tree[x];
        x-=lowbit(x);
    }
    
return ans; } void addz(int x) { while (x<=n) { tree[x]+=1; x+=lowbit(x); } return; } struct Node { int v, ord; bool operator < (const Node x) const { return v<x.v; } }node[MAXN]; int main() { scanf("%d", &n); for (int i=1; i<=n; i++) { scanf(
"%d", &node[i].v); node[i].ord=i; } sort(node+1, node+n+1 ); for (int i=1; i<=n; i++) a[node[i].ord]=i; for (int i=1; i<=n; i++) { addz(a[i]); tot+=i-query(a[i]); } printf("%d", tot); return 0; }
View Code

求逆序對