zoukankan      html  css  js  c++  java
  • P1908 逆序对

    P1908 逆序对

    题意:

    给你一个长度为 $ n $ 的数组,求其中的逆序对数量。

    解法:

    数据范围很大 $ (n leq 5 imes 10^5) $ ,所以考虑离散化+树状数组。

    CODE:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<map>
    
    using namespace std;
    
    #define LL long long
    const int N = 5e5 + 100;
    
    struct Node {
        int val,pos;
    } a[N];
    int tree[N],tag[N],n;
    LL ans;
    
    inline int lowbit(int x) {
        return x & (-x);
    }
    inline void add(int x) {
        for(; x <= n ; x += lowbit(x))
            tree[x]++;
        return;
    }
    inline int query(int x) {
        int ans = 0;
        for(; x ; x -= lowbit(x))
            ans += tree[x];
        return ans;
    }
    inline bool cmp(Node a,Node b) {
        if(a.val == b.val) 
            return a.pos < b.pos;
        return a.val < b.val;
    }
    inline int read() {
        int x = 0,f = 1;
        char ch = getchar();
        while(ch < '0' || ch > '9') {if(ch == '-') f=-1; ch=getchar();}
        while(ch >= '0' && ch <= '9') {x = (x<<1) + (x<<3) + (ch^48);ch = getchar();}
        return x * f;
    }
    
    int main() {
        n = read();
        for(int i = 1 ; i <= n ; i++) {
            a[i].val = read();
            a[i].pos = i;
        }
        sort(a + 1,a + n + 1,cmp);
        for(int i = 1 ; i <= n ; i++) tag[a[i].pos] = i;
        for(int i = n ; i >= 1 ; i--) {
            ans += query(tag[i]);
            add(tag[i]);
        }
        printf("%lld 
    ",ans);
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    锐捷交换机密码恢复
    adobe cs3系列产品官方帮助网页(中文)
    网页设计视频教程
    锐捷交换机、路由器配置手册
    WINPE下如何直接删除联想隐藏分区?
    IWMS实现频道页面的方法
    SATA、SCSI、SAS区别与特点
    自定义系统必备
    自己写的Web服务器
    尝试MVP模式
  • 原文地址:https://www.cnblogs.com/Repulser/p/11469774.html
Copyright © 2011-2022 走看看