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
  • 相关阅读:
    软件概要设计说明书(初稿) 定稿
    重新确定了数据流图以及模块图2020.5.4
    开始编写概要说明书以及详细说明书2020.4.29
    singleflight是如何避免缓存击穿的?
    从IO 到BIO/NIO/AIO 浅析
    JVM
    Http
    Linux命令
    什么时候触发MinorGC?什么时候触发FullGC?
    计算机网络
  • 原文地址:https://www.cnblogs.com/zjzj/p/6931919.html
Copyright © 2011-2022 走看看