Maximizing the Function

Problem Statement :

Consider an array of  binary integers (i.e., 's and 's) defined as .

Let  be the bitwise XOR of all elements in the inclusive range between index  and index  in array . In other words, . Next, we'll define another function, :

Given array  and  independent queries, perform each query on  and print the result on a new line. A query consists of three integers, , , and , and you must find the maximum possible  you can get by changing at most  elements in the array from  to  or from  to .

Note: Each query is independent and considered separately from all other queries, so changes made in one query have no effect on the other queries.

Input Format

The first line contains two space-separated integers denoting the respective values of  (the number of elements in array ) and  (the number of queries).
The second line contains  space-separated integers where element  corresponds to array element  .
Each line  of the  subsequent lines contains  space-separated integers, ,  and  respectively, describing query  .

Output Format

Print  lines where line  contains the answer to query  (i.e., the maximum value of  if no more than  bits are changed).

Solution :


                            Solution in C :

In  C  :

#include <stdio.h>
#include <stdlib.h>
int a[500000],odd_sum[500000],even_sum[500000];

int main(){
  int n,q,x,y,k,odd,even,i;
      printf("%lld\n",(y-x+2)/2*((long long)(y-x+3)/2));
      if(!x || !a[x-1])
        printf("%lld\n",odd*(long long)(even+1));
        printf("%lld\n",even*(long long)(odd+1));
  return 0;

                        Solution in C++ :

In  C++  :

#include "bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pair<int, int> > vpii; typedef long long ll;
template<typename T, typename U> static void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if(x < y) x = y; }

int main() {
	int n; int q;
	while(~scanf("%d%d", &n, &q)) {
		vector<int> a(n);
		for(int i = 0; i < n; ++ i)
			scanf("%d", &a[i]);
		vector<int> sum(n + 1);
		rep(i, n) sum[i + 1] = sum[i] ^ a[i];
		vector<int> sum2(n + 2);
		rep(i, n + 1) sum2[i + 1] = sum2[i] + sum[i];
		rep(ii, q) {
			int x; int y; int k;
			scanf("%d%d%d", &x, &y, &k), ++ y;
			int cnt0 = sum2[y + 1] - sum2[x];
			int cnt1 = (y + 1 - x) - cnt0;
			if(cnt0 > cnt1) swap(cnt0, cnt1);
			ll ans = k == 0 ? (ll)cnt0 * cnt1 :
				(ll)((y + 1 - x) / 2) * ((y + 1 - x + 1) / 2);
			printf("%lld\n", ans);
	return 0;

                        Solution in Java :

In  Java :

import java.util.*;

public class C {

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;

    void solve() throws IOException {
        int n = nextInt();
        int q = nextInt();
        int[] b = new int[n + 1];
        for (int i = 0; i < n; i++) {
            int x = nextInt();
            b[i + 1] = b[i] ^ x;
        int[] c = new int[n + 2];
        for (int i = 0; i < n + 1; i++) {
            c[i + 1] = c[i] + b[i];
        while (q-- > 0) {
            int x = nextInt();
            int y = nextInt();
            int k = nextInt();
            int len = y - x + 2;
            int ones;
            if (k == 0) {
                ones = c[y + 2] - c[x];
            } else {
                ones = len / 2;
            out.println((long)ones * (len - ones));

    C() throws IOException {
        br = new BufferedReader(new InputStreamReader(;
        out = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {
        new C();

    String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
        return st.nextToken();

    String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());

                        Solution in Python : 
In   Python3 :


def init(A,n):
    retA = [0]*(n+1);
    B = [0]*(n+1)
    tmp = 0
    for i in range(n):
        tmp ^= A[i]
        B[i+1] = tmp
        retA[i+1] += retA[i] + tmp

    return retA,B

if __name__ == "__main__":
    n,q = list(map(int,input().rstrip().split()))
    A = list(map(int,input().rstrip().split()))

    newA, B = init( A, n )
    while q > 0 :
        x,y,k = list(map(int,input().rstrip().split()))
        num = newA[y+1] - newA[x]
        if B[x]:
            num = (y + 1 - x) - num
        size = y - x + 2

        num = abs(int(size/2)) if k else num

        print( num*(size-num) )


View More Similar Problems

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →


You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →