如何使用线段树在范围内找到可被 3 整除的元素数?

问题描述

我正在学习线段树算法并尝试使用它解决问题。这个问题要求我输出给定范围内可被 3 整除的元素数。我认为我的逻辑是正确的,但它没有输出正确的结果。

如果输入数组是 4 -9 3 7 1 0 2 并且给定的范围是 1-4,它应该输出 1,因为只有 -9 可以被 3 整除。

#include <bits/stdc++.h>
#define mx 100005
typedef long long int ll;
using namespace std;
ll arr[mx];
ll tree[mx*3];

void init(int node,int b,int e){
    if(b == e){
        tree[node] = arr[b];
        return;
    }
    else{
        int Left = node*2;
        int Right = (node*2)+1;
        int mid = (b + e)>>1;

        init(Left,b,mid);
        init(Right,mid+1,e);

        int cnt = 0;
        if(tree[Left]%3 == 0)cnt++;
        if(tree[Right]%3 == 0)cnt++;
        tree[node] = cnt;
    }
}


int divQuery(int node,int e,int i,int j){
    if(i>e || j<b)return;
    if(b>=i && e<=j)return tree[node];

    int Left = node*2;
    int Right = (node*2)+1;
    int mid = (b + e)>>1;

    int data1 = divQuery(Left,mid,i,j);
    int data2 = divQuery(Right,e,j);
    return data1+data2;
}

int main(){
    int n; cin>>n;
    for(int i=1; i<=n; i++)cin>>arr[i];
    // 4 -9 3 7 1 0 2
    init(1,1,n);
    cout<<divQuery(1,n,2,4)<<endl;

    return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)