Staircase Patterns#4073

Staircase Patterns (Editorial)

The numbers written on the steps are integers and fall within the range from to 10^6 inclusive.

We will construct a Fenwick tree on an array of length 10^6 + 1 (with indices ranging from to 10^6 inclusive), initially filled with zeros.

Each time the detective steps on a stair with the value , we increase a_{value} by . At the same time, he records the sum in his notebook:

a_0 + a_1 + a_2 + ... + a_{value - 1}

Given the input constraints, all calculations should be performed using a -bit integer type.

Example

Let's simulate the detective's recordings using the given example. The array indexing starts from . The numbers recorded by the detective are shown under the arrows.

The sum of the numbers written in the detective's notebook is

0 + 1 + 1 + 9 + 4 = 15

Algorithm implementation

Let the maximum array size be . Create a Fenwick tree Fenwick.

#define MAX 1000001
vector<long long> Fenwick;

The function Summa0_i computes the sum a_0 + a_1 + ... + a_i.

long long Summma0_i(int i)
{
  long long result = 0;
  for (; i >= 0; i = (i & (i + 1)) - 1)
    result += Fenwick[i];
  return result;
}

The function IncElement increases the value of an element: a_i = a_i + delta.

void IncElement(int i, int delta)
{
  for (; i < MAX; i = (i | (i+1)))
    Fenwick[i] += delta;
}

The main part of the program. Read the input data.

scanf("%d",&tests);
while (tests--)
{
  scanf("%d",&n);

Initialize the Fenwick array with zeros.

  Fenwick.assign(MAX,0);

The desired sum recorded in the detective's notebook will be computed in the variable .

  sum = 0;

Process the numbers written on the steps one by one.

  for (i = 0; i < n; i++)
  {

For each , written on a step, increase a_{value} by and compute the sum of all previously encountered numbers smaller than . This sum is a_0 + a_1 + a_2 + ... + a_{value - 1}.

    scanf("%d",&value);
    IncElement(value, value);
    sum += Summma0_i(value - 1);
  }

Print the total sum of all numbers written in the detective's notebook.

  printf("%lld\n",sum);
}