Count of even sum triplets in the array for Q range queries | C ++ program for above approach ; Function to count number of triplets with even sum in range l , r for each query ; Initialization of array ; Initialization of variables ; Traversing array ; If element is odd ; If element is even ; Storing count of even and odd till each i ; Traversing each query ; Count of odd numbers in l to r ; Count of even numbers in l to r ; Finding the ans ; Printing the ans ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countTriplets ( int size , int queries , int arr [ ] , int Q [ ] [ 2 ] ) { int arr_even [ size + 1 ] , arr_odd [ size + 1 ] ; int even = 0 , odd = 0 ; arr_even [ 0 ] = 0 ; arr_odd [ 0 ] = 0 ; for ( int i = 0 ; i < size ; i ++ ) { if ( arr [ i ] % 2 ) { odd ++ ; } else { even ++ ; } arr_even [ i + 1 ] = even ; arr_odd [ i + 1 ] = odd ; } for ( int i = 0 ; i < queries ; i ++ ) { int l = Q [ i ] [ 0 ] , r = Q [ i ] [ 1 ] ; int odd = arr_odd [ r ] - arr_odd [ l - 1 ] ; int even = arr_even [ r ] - arr_even [ l - 1 ] ; int ans = ( even * ( even - 1 ) * ( even - 2 ) ) / 6 + ( odd * ( odd - 1 ) / 2 ) * even ; cout << ans << " ▁ " ; } } int main ( ) { int N = 6 , Q = 2 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int queries [ ] [ 2 ] = { { 1 , 3 } , { 2 , 5 } } ; countTriplets ( N , Q , arr , queries ) ; return 0 ; }