zoukankan      html  css  js  c++  java
  • 求逆序对模板

    方法一:离散化+树状数组

    模板如下:

    #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

    方法二:归并排序

    模板如下:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int n,A[40010],T[40010],num;
    
    void merge_sort(int x,int y){
        if(y-x>1){
            int mid=x+(y-x)/2;
            int p=x,q=mid,i=x;
            merge_sort(x,mid);
            merge_sort(mid,y);
            while(p<mid||q<y){
                if(q>=y||(p<mid&&A[p]<=A[q]))
                      T[i++]=A[p++];
                else {T[i++]=A[q++];num+=mid-p;}
            }
            for(i=x;i<y;i++) A[i]=T[i];
        }
    }
    
    int main(){
        cin>>n;
        for(int i=1;i<=n;i++)
            scanf("%d",&A[i]);
        merge_sort(1,n+1);
        cout<<num<<endl;
        return 0;
    }
    View Code
  • 相关阅读:
    Web学习之css
    Spring学习之第一个hello world程序
    MySQL基础学习总结
    Jmeter参数化
    mysql慢查询解析-linux命令
    mysql慢查询
    mysql_存储引擎层-innodb buffer pool
    mysql_Qcahce
    memocached基础操作
    Memcached安装配置
  • 原文地址:https://www.cnblogs.com/zjzj/p/6931919.html
Copyright © 2011-2022 走看看