分段树中的大值用于产品范围查询

时间:2013-08-10 20:19:49

标签: algorithm modular-arithmetic segment-tree

我编写了用于在数组上触发产品范围查询的代码。

注意:此问题与Multiplication in a range不重复。我的问题是不同的

我为此编写了代码,

// Program to show segment tree operations like construction, query and update
#include <stdio.h>
#include <math.h>
#define R 1000000000

typedef unsigned long long ull;
int getMid(int s, int e) {  return s + (e -s)/2;  }

ull getProdUtil(ull *st, int ss, int se, int qs, int qe, int index)
{
    if (qs <= ss && qe >= se)
        return st[index];
    if (se < qs || ss > qe)
        return 1;
    int mid = getMid(ss, se);
    return (getProdUtil(st, ss, mid, qs, qe, 2*index+1) %R *
           getProdUtil(st, mid+1, se, qs, qe, 2*index+2) % R )%R;
}


ull getProd(ull *st, int n, int qs, int qe)
{
    if (qs < 0 || qe > n-1 || qs > qe)
    {
        return 0;
    }

    return getProdUtil(st, 0, n-1, qs, qe, 0) % R;
}


ull constructSTUtil(ull arr[], int ss, int se, ull *st, int si)
{

    if (ss == se)
    {
        st[si] = arr[ss];
        return arr[ss];
    }

    int mid = getMid(ss, se);

    ull l = (ull)constructSTUtil(arr, ss, mid, st, si*2+1)%R;
    ull r = (ull)constructSTUtil(arr, mid+1, se, st, si*2+2)%R;
    st[si] =  (l * r) % R;
    return st[si];
}

void init_array(ull *st, ull size){
    for(ull i=0;i< size;i++){
        st[i] = 1;
    }
}


ull *constructST(ull arr[], int n)
{

    int x = (int)(ceil(log2(n))); //Height of segment tree
    int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree
    ull *st = new ull[max_size];
    init_array(st, max_size);
    constructSTUtil(arr, 0, n-1, st, 0);

    return st;
}

void print_array(ull *array,int size){
    printf("\n");
    for(int i=0; i< size;i++){
        printf("<%d,%llu> ", i+1,array[i]);
    }

}

int main()
{
    int n;
    scanf("%d",&n);

    ull arr[n];

    for(int i=0;i<n;i++){
        scanf("%llu",&arr[i]);
    }

    ull *st = constructST(arr, n);

    int t;
    scanf("%d", &t);

    while(t--){

        int l,m,r;
        scanf("%d %d %d", &l,&r,&m);

        ull result = getProd(st, n, l-1, r-1);

        printf("%lld\n",result % m);

        //int sizes = 100;
        //printf("%llu\n",st[0]);
        //print_array(st, sizes);

    }

    return 0;
}


The constraints are,
1 ≤ N ≤ 100,000 (size of array)
1 ≤ Ai ≤ 100 (array elements)
1 ≤ T ≤ 100,000 (number of test cases)
1 ≤ Li ≤ Ri ≤ N (Left and right ranges in query)
1 ≤ Mi ≤ 10<sup>9</sup> (Modulus for each test case. Each test case has to be modulu of this number)

我很确定我选择的R是一些测试用例失败的。我也用10 18 尝试了R.但还是同样的问题。不知道为什么会这样?

我的问题是,是我选择的R的问题还是在每个测试用例中传递不同M的问题。

注意:真的不期待解决方案,只是期待一个线索

此致

0 个答案:

没有答案