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 :



title-img


                            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;
  scanf("%d%d",&n,&q);
  for(i=0;i<n;i++){
    scanf("%d",a+i);
    if(i){
      a[i]^=a[i-1];
      if(a[i]){
        odd_sum[i]=odd_sum[i-1]+1;
        even_sum[i]=even_sum[i-1];
      }
      else{
        odd_sum[i]=odd_sum[i-1];
        even_sum[i]=even_sum[i-1]+1;
      }
    }
    else
      if(a[i]){
        odd_sum[i]=1;
        even_sum[i]=0;
      }
      else{
        odd_sum[i]=0;
        even_sum[i]=1;
      }
  }
  while(q--){
    scanf("%d%d%d",&x,&y,&k);
    if(k)
      printf("%lld\n",(y-x+2)/2*((long long)(y-x+3)/2));
    else{
      odd=odd_sum[y];
      even=even_sum[y];
      if(x){
        odd-=odd_sum[x-1];
        even-=even_sum[x-1];
      }
      if(!x || !a[x-1])
        printf("%lld\n",odd*(long long)(even+1));
      else
        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.io.*;
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(System.in));
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    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 :






#!/usr/bin/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) )

        q-=1
                    


View More Similar Problems

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 →

Waiter

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 →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →