Вы находитесь на странице: 1из 7

int getSum(int BITree[], int index)

int sum = 0; // Iniialize result

// index in BITree[] is 1 more than the index in arr[]

index = index + 1;

// Traverse ancestors of BITree[index]

while (index>0)

// Add current element of BITree to sum

sum += BITree[index];

// Move index to parent node in getSum View

index -= index & (-index);

return sum;

// Updates a node in Binary Index Tree (BITree) at given index

// in BITree. The given value 'val' is added to BITree[i] and

// all of its ancestors in tree.

void updateBIT(int BITree[], int n, int index, int val)

// index in BITree[] is 1 more than the index in arr[]

index = index + 1;

// Traverse all ancestors and add 'val'

while (index <= n)

// Add 'val' to current node of BI Tree


BITree[index] += val;

// Update index to that of parent in update View

index += index & (-index);

// Constructs and returns a Binary Indexed Tree for given

// array of size n.

int *constructBITree(int arr[], int n)

// Create and initialize BITree[] as 0

int *BITree = new int[n+1];

for (int i=1; i<=n; i++)

BITree[i] = 0;

// Store the actual values in BITree[] using update()

for (int i=0; i<n; i++)

updateBIT(BITree, n, i, arr[i]);

// Uncomment below lines to see contents of BITree[]

//for (int i=1; i<=n; i++)

// cout << BITree[i] << " ";

return BITree;

// Driver program to test above functions

int main()

{
int n ;

cin>>n;

int arr[n]={0};

int *BITree = constructBITree(arr[], n);

int real[n];

for(int i=0;i<n;i++)

cin>>real[i];

updateBIT(BITree, n, i, 1);

int count[n]={0};int x,y;

x=getsum(BITree,0);

y=0;

for(int i=1;i<n;i++)

count[i]=getsum(BITree,i);

if(count[i]>x)

x=count[i];

y=i;

count[i]=0;

int m=count[0],n=0;

for(int i=1;(i<n)&&(i!=y);i++)
{

count[i]=getsum(BITree,i);

if(count[i]>m)

m=count[i];

n=i;

cout<<x<<" "<<m;

return 0;

New

#include <iostream>

using namespace std;

int*constructtree(int n)

int arr[n]={[0,n-1]=0};
return arr;

int*update(int *bit,int n, int val, int index)

while(index<n)

bit[index]=bit[index]+val;

index=index+index&(-index);

int sum(int*bit,int index)

int sum=0;

while(index>0)

sum=sum+bit[index];

index=index-index&(-index);

return sum;

int rangesum(int*bit,int a, int b)

int sum=sum(bit, b)-sum(bit,a-1);

return sum;

int main() {

// your code goes here

return 0;

//

#include<bits/stdc++.h>
using namespace std;

int *ctree(int n )

{ int p=2*n;

int *arr=new int[p];

memset(arr,0,p);

return arr;

void update(int *arr,int index, int n)

while(index<=n)

arr[index]=arr[index]+1;

index += (index & -index);

int fsum(int *arr,int index)

int sum=0;

while(index>0)

sum=sum+arr[index];

index -= (index & -index);

return sum;

}
int main() {

int n;

cin>>n;

int *bit=ctree(n);

int r,x,sum=0;

for(int i=0;i<n;i++)

cin>>r;

x=fsum(bit,n)-fsum(bit,r-1);

sum=sum+x;

update(bit,r,n);

cout<<sum;

return 0;

Вам также может понравиться