poj 2299 Ultra-QuickSort(逆序对)

【题目大意】:给你n个数,求其逆序对


【解题思路】:归并排序或者树状数组


【代码】:

//树状数组
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

struct Node
{
    int v,x;
};

int c[500100],n;
int aa[500100];
Node a[500100];
ll ans;

bool cmp(const Node &a,const Node &b){
    return a.v<b.v;
}

void update(int x,int val){
    for(int i=x;i<=n;i+=lowbit(i)){
        c[i]+=val;
    }
}

int getsum(int x){
    int temp=0;
    for(int i=x;i>=1;i-=lowbit(i)){
        temp+=c[i];
    }
    return temp;
}

int main(){
    while(~scanf("%d",&n)){
        if (n==0) break;
        for (int i=1; i<=n; i++){
            scanf("%d",&a[i].v);
            a[i].x=i;
        }
        sort(a+1,a+n+1,cmp);
        for (int i=1; i<=n; i++)
            aa[a[i].x]=i;
        memset(c,0,sizeof(c));
        ans=0;
        for (int i=1; i<=n; i++){
            update(aa[i],1);
            ans+=i-getsum(aa[i]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


//归并排序
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

int a[500100],b[500100];
ll ans;
int n;

void solve_mergesort(int l,int r){
    int i,j,k,m;
    if (l>=r) return ;
    m=(l+r)/2;
    solve_mergesort(l,m);
    solve_mergesort(m+1,r);
    i=l;
    j=m+1;
    k=l;
    do{
        if (a[i]>a[j]){
            b[k]=a[j];
            ans+=m-i+1;
            j++;
            k++;
        }
        else{
            b[k]=a[i];
            k++;
            i++;
        }
    } while (i<=m && j<=r);
    while (i<=m){
        b[k]=a[i];
        k++;
        i++;
    }
    while (j<=r){
        b[k]=a[j];
        k++;
        j++;
    }
    for (int i=l; i<=r; i++) a[i]=b[i];
    return ;
}

int main() {
    while (~scanf("%d",&n)){
        if (n==0) break;
        for (int i=0; i<n; i++) scanf("%d",&a[i]);
        ans=0;
        solve_mergesort(0,n-1);
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(c)