题解 | #小红的子序列逆序对#

小红的子序列逆序对

https://www.nowcoder.com/practice/189a109747604763932024984f856d99

import java.io.*;
import java.util.*;
import java.math.BigInteger;

public class Main {
    static int N = 100010;
    static int mod = (int)(1e9+7);
    static int n;
    static int[] a = new int[N];
    static long[] tr = new long[N];
    
    static int lowbit(int x) {
        return x & -x;
    } 

    static void add(int x, long v) {
        for(int i=x;i<N;i+=lowbit(i)){
            tr[i] += v;        
        }
    }

    static long query(int x) {
        long res = 0;
        for(int i=x;i>0;i-=lowbit(i)) {
            res += tr[i];
        }
        return res;
    }

    static void solve() {
        n = in.nextInt(); 
        long ans = 0, cnt = 1;
        for(int i=1;i<=n;i++) {
            a[i] = in.nextInt();
            add(a[i],1);
            ans += i-query(a[i]);
        }
        for(int i=2;i<n;i++) {
            cnt = cnt*2%mod;
        }
        out.println(ans%mod*cnt%mod);
    }   

    public static void main(String[] args) {
        solve();
        out.flush();
    }

    static FastReader in = new FastReader();
    static PrintWriter out = new PrintWriter(System.out);

    static class FastReader {
        static BufferedReader br;
        static StringTokenizer st;

        FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            String str = "";
            while (st == null || !st.hasMoreElements()) {
                try {
                    str = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                st = new StringTokenizer(str);
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}

全部评论

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
object3:开始给部分🌸孝子上人生第一课了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务