I am trying to solve a problem that looks something like this:
I have been given n numbers (1 <= n <= 10 ^ 5). I need to write down the sum of all the numbers on the left that are less than the current number and repeat the process for all n numbers. Then I must find the sum of all previously received amounts. (Each number is N, 0 <= N <= 10 ^ 6).
For instance,
1 5 3 6 4 less1 less5 less3 less6 less4 (0) + (1) + (1)+(1+5+3)+(1+3) 0 + 1 + 1 + 9 + 4 = 15
A trivial solution to this problem will be to start two cycles and for each given number to find the sum of all numbers less than this number, and finally, give the sum of these sums as an output. The complexity of time is O (n ^ 2).
I think the best O (nlogn) solution for this problem is using a binary indexed tree (Fenwick Tree). For each number, I will add each of the numbers to the global array a and perform two obvious BIT operations. I believe that the time complexity of this algorithm is O (nlogn), which, if true, is obviously better than the previous O (n ^ 2).
I implemented the code in C ++.
#include<iostream>
I have two questions:
First, am I doing it right? / Is my logic correct?
Secondly, if I'm right about O (nlogn) time complexity, then why is it running slowly? Can you help me with further optimizations?
Retrieved from 1.41 seconds. At the same time, I updated my final accepted code. Any suggestion for optimization?
Based on the comments, I tried my own function for faster I / O, but still it won't do me any good. This is my function for quick I / O:
inline int read(){ char c=getchar_unlocked(); int n=0; while(!(c>='0' && c<='9')) c=getchar_unlocked(); while(c>='0' && c<='9'){ n=n*10 + (c-'0'); c=getchar_unlocked(); } return n; }
This is the link to the problem:
http://www.spoj.pl/problems/DCEPC206/
If there is anyone who decided to solve it, let me know. Thanks.