1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
#include <iostream>
#include "message.h"
#include "teatr.h"

const int MAXV = 1048576;
const int MAX = 1000005;

struct RT
{
    void insert(int x)
    {
        x += MAXV;
        while (x > 0)
        {
            T[x] += 1;
            x /= 2;
        }
    }
    int check(int a, int b)
    {
        a += MAXV;
        b += MAXV;
        int result = T[a];
        if (a!=b) result += T[b];
        while (a/2 < b/2)
        {
            if (a%2 == 0) result += T[a+1];
            if (b%2 == 1) result += T[b-1];
            a /= 2;
            b /= 2;
        }
        return result;
    }
    int T[MAXV*2];
};

int n;
int id;
int nodes;
RT rt;
int C[MAX];
int D[MAX];

int main()
{
    //std::ios_base::sync_with_stdio(0);
    nodes = NumberOfNodes();
    id = MyNodeId();

    n = GetN();
    int n0 = (n+nodes-1) / nodes;
    int i0 = id * n0;

    if (i0 >= n)
    {
        n0 = 0;
        i0 = 0;
    }
    long long result = 0;
    // std::clog << " :: " << id << " :: " << i0 << " .. " << std::min(i0+n0, n) << std::endl;

    for (int i=i0;i<i0+n0 && i<n;++i)
    {
        int x = GetElement(i);
        ++C[x];
        result += rt.check(x+1, MAXV-1);
        rt.insert(x);
    }
    // std::clog << " :: " << id << " :: block = " << result << std::endl;
    for (int i=0;i<i0;++i)
    {
        int x = GetElement(i);
        ++D[x];
    }
    for (int i=MAX-2;i>=0;--i)
    {
        D[i] += D[i+1];
    }
    long long c = 0;
    for (int i=1;i<MAX-1;++i)
    {
        c = C[i];
        result += c * D[i+1];

        // if (c*D[i+1] != 0)
        // {
        //     std::clog << " :: " << id << " :: " << c << " * " << D[i+1] << std::endl;
        // }
    }

    if (id == 0)
    {
        for (int i=1;i<nodes;++i)
        {
            Receive(i);
            result += GetLL(i);
        }
        std::cout << result << std::endl;
    }
    else
    {
        PutLL(0, result);
        Send(0);
    }
    
    return 0;
}