Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.util.Arrays;
- import java.util.Locale;
- import java.util.StringTokenizer;
- public class InversionsDoubles {
- private void solve() throws IOException {
- int n = readInt();
- int[] p = new int[n];
- for (int i = 0; i < n; i++) {
- p[i] = readInt() - 1;
- }
- long inversions = 0;
- FenwickTree invTree = new FenwickTree(n);
- for (int i = n - 1; i >= 0; i--) {
- inversions += invTree.sum(p[i]);
- invTree.add(p[i], 1);
- }
- double mult = 1.0 / n / (n + 1); // 2.0 instead of 1.0 for reverse
- double add = 0;
- double sub = 0;
- FenwickTree sumTree = new FenwickTree(n);
- for (int i = n - 1; i >= 0; i--) {
- add += sumTree.sum(p[i], n - 1) * mult * (i + 1);
- sub += sumTree.sum(p[i]) * mult * (i + 1);
- sumTree.add(p[i], n - i);
- }
- double ans = inversions + add - sub;
- out.printf(Locale.US, "%.15f\n", ans);
- }
- private static class FenwickTree {
- private int n;
- private long[] t;
- private FenwickTree(int n) {
- this.n = n;
- this.t = new long[n + 1];
- }
- private void add(int i, long d) {
- i++;
- while (i <= n) {
- t[i] += d;
- i += Integer.lowestOneBit(i);
- }
- }
- private long sum(int r) {
- r++;
- long ans = 0;
- while (r > 0) {
- ans += t[r];
- r -= Integer.lowestOneBit(r);
- }
- return ans;
- }
- private long sum(int l, int r) {
- return sum(r) - sum(l - 1);
- }
- @Override
- public String toString() {
- long[] s = new long[n];
- for (int i = 0; i < n; i++) {
- s[i] = sum(i, i);
- }
- return Arrays.toString(s);
- }
- }
- //------------------------------------------------------------------------------
- public static void main(String[] args) {
- new InversionsDoubles().run();
- }
- private void run() {
- try {
- initIO();
- solve();
- in.close();
- out.close();
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
- private BufferedReader in;
- private StringTokenizer tok;
- private PrintWriter out;
- private void initIO() throws IOException {
- in = new BufferedReader(new InputStreamReader(System.in));
- out = new PrintWriter(System.out);
- // in = new BufferedReader(new FileReader(new File("input.txt")));
- // out = new PrintWriter(new File("output.txt"));
- }
- private String readString() throws IOException {
- while (tok == null || !tok.hasMoreTokens()) {
- tok = new StringTokenizer(in.readLine());
- }
- return tok.nextToken();
- }
- @SuppressWarnings("unused")
- private int readInt() throws IOException {
- return Integer.parseInt(readString());
- }
- @SuppressWarnings("unused")
- private long readLong() throws IOException {
- return Integer.parseInt(readString());
- }
- @SuppressWarnings("unused")
- private double readDouble() throws IOException {
- return Double.parseDouble(readString());
- }
- }
Add Comment
Please, Sign In to add comment