首页 > 解决方案 > 使用稀疏表的范围最大和查询

问题描述

我使用稀疏表实现了范围最大和查询,我知道更有效的方法是使用段树。

我试过的:

我正在计算(i,2^j-1)i 和 j 的所有可能值的范围内的最大总和,并将它们存储在表中

其中 i 是索引,j 表示 2 的幂(2^j 表示从 i 开始计算最大总和的段的长度)

现在使用上表我们可以回答查询

输入:

3

-1 2 3

1

1 2

预期输出:

2

实际输出:

“错误答案(垃圾值)”

我们实际上必须告诉给定查询中的最大连续总和 Link to the ques spoj gss1

请帮忙:

#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;
}

链接到问题Spoj Gss1

标签: c++range-query

解决方案


推荐阅读