I came across this question while practicing, I’m not familiar with fenwick trees. Can someone explain why my code is not working with arrays?

  arrays, c++, cp, fenwick-tree, tree

Problem

There are N soldiers located on our X-AXIS. The point at which soldier is located also has some number of bombs.
The war is near and every soldier wants to communicate with every other soldier.
If the ith soldier has b number of bombs and is located at position X then the cost of communicating with any other soldier j having c number of bombs located at position Y is defined as |X-Y|*max(b,c).
Find the sum of costs of communication if every soldier wants to communicate with every other soldier.
NOTE :- You have to consider pair(i,j) only once in sum of costs.

Input Format
First line consists of number of test cases T. Each test case consists of three lines. The first line indicates the number of soldiers (N). The second line indicates the coordinates of the N soldiers ( X[i] ). The third line contains the number of bombs at every soldiers location ( B[i] ) . The x-coordinates needn’t be in increasing order in the input.

Constraints
1 <= T <= 20 1 <= N <= 200000 1 <= X[i] <= 1000000000 1 <= B[i] <= 10000

Output Format
The total cost modulo 10^9+7.

Solution

#include<iostream>
#include<math.h>
using namespace std;
int main() {
    int max (int, int);
    int tc;
    cin>>tc;
    while (tc--)
    {
        int n;
        long sum = 0;
        cin>>n;
        long arr[3][n];
        for (int i = 0; i < n; ++i){
            cin>>arr[0][i];
        }
        for (int i = 0; i < n; ++i){
            cin>>arr[1][i];
        }
        if (n == 1){
            sum = arr[0][0]*arr[1][0];
        }
        for (int i = 0; i < n-1; ++i){
            for (int j = i+1; j<n; ++j){
            arr[2][j] = abs(arr[0][j] -arr[0][i])*max(arr[1][i], arr[1][j]);
            sum += arr[2][j];
            }
        }
        cout<<sum<<endl;
    }
    return 0;
}
int max(int a, int b){
    return a > b ? a : b;
}

Error: TLE

Source: Windows Questions C++

LEAVE A COMMENT