12341c0des
12341c0des

Reputation: 31

Range max sum query using sparse table

I Implemented range max sum query using sparse Table ,I Know more efficient approach would be using segment trees.

What I have tried:

I am calculating the max sum in the range (i,2^j-1) for all possible value of i and j and storing them in a table

where i is the index and j denotes the power of 2 (2^j denotes the length of segment from i for which we are calculating max sum)

Now using the above table we can answer the queries

Input:

3

-1 2 3

1

1 2

expected output:

2

actual output:

"wrong answer(garbage value)"

we actually have to tell the max contiguous sum in a given query Link to the ques spoj gss1

Please help:

#include<iostream>
#include<vector>
#include<algorithm>
#include<climits>
using namespace std;
const int k = 16;
const int N = 1e5;
const int ZERO = 0; // ZERO + x = x + ZERO = x (for any x)

long long table[N][k + 1]; // k + 1 because we need to access table[r][k]
long long  Arr[N];

int main()
{
    int n, L, R, q;
    cin >> n; // array size
    for(int i = 0; i < n; i++)
        cin >> Arr[i];

    // build Sparse Table
    for(int i = 0; i < n; i++)
        table[i][0] = Arr[i];

    for(int j = 1; j <= k; j++) {
        for(int i = 0; i <= n - (1 << j); i++)
            //table[i][j] = table[i][j - 1] + table[i + (1 << (j - 1))][j - 1];
            table[i][j] = max(table[i][j-1],max(table[i+(1<<(j-1))][j-1],table[i+(1<<(j-1))][j-1]+table[i][j-1]));
    }

    cin >> q; // number of queries
    for(int i = 0; i < q; i++) {
        cin >> L >> R; // boundaries of next query, 0-indexed
        long long int answer = LLONG_MIN;
        for(int j = k; j >= 0; j--) {
            if(L + (1 << j) - 1 <= R) {
                answer = max(answer,answer + table[L][j]);
                L += 1 << j; // instead of having L', we increment L directly
            }
        }
        cout << answer << endl;
    }
    return 0;
}

link to the question Spoj Gss1

Upvotes: 3

Views: 426

Answers (0)

Related Questions