Changing Bits


Problem Statement :


Let a and b be binary numbers of length n (MSB to the left). The following commands may be performed:

set_a idx x: Set  to , where  and  is  least significant bit of .
set_b idx x: Set  to , where  and  is  least significant bit of .
get_c idx: Print , where  and .
Given , and a list of commands, create a string made of the results of each  call, the only command that produces output. For example,  and  so the length of the numbers is . Print an answer string that contains the results of all commands on one line. A series of commands and their results follow:

Starting
ans = '' (empty string)
a b
000 111
set_a 1 1
010 111
set_b 0 1
010 111
get_c 3
a + b = 1001
ans = '1'
010 111
get_c 4
a + b = 01001
ans = '10'

Note: When the command is get_c 4,  had to be padded to the left with a  to be long enough to return a value.

Function Description

Complete the changeBits function in the editor below. For each get_c command, it should print either a 0 or a 1 without a newline until all commands have been processed. At that point, add a newline.

changeBits has the following parameters:
- a, b: two integers represented as binary strings
- queries[queries[0]-queries[n-1]]: an array of query strings in the format described

Input Format

The first line of input contains two space-separated integers,  and , the length of the binary representations of  and , and the number of commands, respectively.
The second and third lines each contain a string representation of  and .
The following  lines each contain a command string  as described above.


Output Format

For each query of the type , output a single digit 0 or 1. Output must be placed on a single line.



Solution :



title-img


                            Solution in C :

In  C  :






#define MAX_NUM ((unsigned int)-1)
#define WORD_SIZE 32
#define DATA_TYPE unsigned int
#include <stdio.h>
int main()
{
    DATA_TYPE A[3500] = {0}, B[3500] = {0}, C[3500] = {0};
    unsigned int CARRY[3500] = {0};
    int N, Q, N2;
    int idx, x, lowest_modified_idx=0;
    int i, j, rem;
    char cmd[10];
    char bit_string[100001];
    scanf("%d %d", &N, &Q);
    scanf("%s", bit_string);
    N2 = N/WORD_SIZE;
    rem = N % WORD_SIZE;

    for ( i = 0 ; i < N2 ; ++i )
        for ( j = 0 ; j < WORD_SIZE ; ++j )
            if ( bit_string[N - 1 - (i*WORD_SIZE + j)] == '1' )
                A[i] |= 1ULL << j;
    if ( rem )
        for ( j = 0 ; j < rem ; ++j )
            if ( bit_string[ rem - j - 1 ] == '1' )
                A[N2] |= 1ULL << j;
        
    
    scanf("%s", bit_string);

    for ( i = 0 ; i < N2 ; ++i )
        for ( j = 0 ; j < WORD_SIZE ; ++j )
            if ( bit_string[N - 1 - (i*WORD_SIZE + j)] == '1' )
                B[i] |= 1ULL << j;
    if ( rem )
        for ( j = 0 ; j < rem ; ++j )
            if ( bit_string[ rem - j - 1 ] == '1' )
                B[N2] |= 1ULL << j;    
    
    for ( ; Q ; --Q )
    {
        scanf("%s %d", cmd, &idx);
        switch(cmd[4])
        {
        case 'a':
            scanf("%d", &x);
            if ( x == 1 )
                A[idx/WORD_SIZE] |= (1ULL << (idx%WORD_SIZE));
            else
                A[idx/WORD_SIZE] &= ~(1ULL << (idx%WORD_SIZE));
            if ( idx < lowest_modified_idx )
              lowest_modified_idx = idx;
            break;
        case 'b':
            scanf("%d", &x);
            if ( x == 1 )
                B[idx/WORD_SIZE] |= (1ULL << (idx%WORD_SIZE));
            else
                B[idx/WORD_SIZE] &= ~(1ULL << (idx%WORD_SIZE));
            if ( idx < lowest_modified_idx )
              lowest_modified_idx = idx;
            break;
            
        case 'c':
            if ( idx >= lowest_modified_idx )
            { for ( i = lowest_modified_idx/WORD_SIZE ; i <= idx/WORD_SIZE ; ++i )
              {
                  CARRY[i+1] = 0;
                  if ( MAX_NUM - A[i] < B[i])
                     CARRY[i+1] = 1;
                  else if (A[i] < B[i] )
                  {    if ( MAX_NUM - A[i] - CARRY[i] < B[i] )
                          CARRY[i+1] = 1;
                  }
                  else if ( MAX_NUM - B[i] - CARRY[i] < A[i] )
                  {    CARRY[i+1] = 1;
                  }
                  C[i] = A[i] + B[i] + CARRY[i];
              }
              lowest_modified_idx = idx;
            }
            printf("%d", (C[idx/WORD_SIZE] & (1ULL << (idx%WORD_SIZE)))?1:0);
            break;
//        case 'd':
//            for ( j = rem ; j >= 0 ; --j )
//              printf("%d", (C[N/WORD_SIZE] & (1<<(j)))?1:0);
//              
//            for ( i = N/WORD_SIZE - 1 ; i >= 0; --i )
//              for ( j = WORD_SIZE-1;  j >= 0 ; --j )
//                printf("%d", (C[i] & (1<<j))?1:0);
//            printf("\n");
//            break;
        }
    }
}
                        


                        Solution in C++ :

In  C++  :







#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int maxn = 100010;
int a[maxn], b[maxn], c[maxn];
int n, q;
char ss[maxn*5];
int l[maxn*2], r[maxn*2], s[maxn*2], tn;

int build(int ll, int rr)
{
	if(ll>=rr)
		return -1;
	int ret = tn++;
	if(ll + 1 == rr)
	{
		l[ret] = r[ret] = -1;
		s[ret] = c[ll];
		return ret;
	}
	int mid = (ll + rr) / 2;
	l[ret] = build(ll, mid);
	r[ret] = build(mid, rr);
	s[ret] = (s[l[ret]] == s[r[ret]] ? s[l[ret]] : 2);
	return ret;
}

void init() {
	scanf("%d%d", &n, &q);
	//printf("%d %d\n", n, q);
	memset(c, 0, sizeof(c));
	scanf("%s", ss);
	//printf("%s\n", ss);
	for(int i=0; i<n; ++i) {
		a[i] = c[i] = ss[n - i - 1] - '0';
	}
	scanf("%s", ss);
	//printf("%s\n", ss);
	for(int i=0; i<n; ++i) {
		b[i] = ss[n - 1 - i] - '0';
		c[i] += ss[n - 1 - i] - '0';
		if(c[i] >= 2)
		{
			c[i] -= 2;
			c[i+1] ++;
		}
	}
	a[n] = b[n] = 0;
	//memset(a, 0, sizeof(a));
	//memset(b, 0, sizeof(b));
	//memset(c, 0, sizeof(c));
	n++;
	tn = 0;
	build(0, n);
}

void push_down(int id) {
	if(s[id] == 2)
		return;
	if(l[id] < 0)
		return;
	s[l[id]] = s[r[id]] = s[id];
}

int findright(int id, int ll, int rr, int i, int bit)
{
	if(rr <= i)
		return -1;
	if(s[id] == bit)
		return i < ll ? ll : i;
	if(s[id] == (bit ^ 1))
		return -1;
	push_down(id);
	int mid = (ll + rr) / 2;
	int t = findright(l[id], ll, mid, i, bit);
	if(t >= 0)
		return t;
	return findright(r[id], mid, rr, i, bit);
}

void change(int id, int ll, int rr, int bl, int br, int bit)
{
	if(br <= ll || rr <= bl)
		return;
	if(bl <= ll && rr <= br)
	{
		s[id] = bit;
		return;
	}
	push_down(id);
	int mid = (ll + rr) / 2;
	change(l[id], ll, mid, bl, br, bit);
	change(r[id], mid, rr, bl, br, bit);
	if(s[l[id]] == s[r[id]])
		s[id] = s[l[id]];
	else
		s[id] = 2;
}

int getbit(int id, int ll, int rr, int i)
{
	if(i<ll || i>=rr)
		return 0;
	if(s[id] < 2)
		return s[id];
	int mid = (ll + rr) / 2;
	if(i < mid)
		return getbit(l[id], ll, mid, i);
	else
		return getbit(r[id], mid, rr, i);
}

void work() {
	int i, bit;
	int pn = 0;
	char cmd[10];
	while(q--) {
		scanf("%s", cmd);
		//printf("%s ", cmd);
		if(cmd[4]=='a' || cmd[4] == 'b')
		{
			scanf("%d%d", &i, &bit);
			//printf("%d %d\n", i, bit);
			if(cmd[4] == 'a' && a[i] == bit)
				continue;
			if(cmd[4] == 'b' && b[i] == bit)
				continue;
			if(cmd[4] == 'a') a[i] = bit;
			else b[i] = bit;
			int lmb = findright(0, 0, n, i, bit ^ 1);
			if(lmb == -1)
				lmb = n;
			change(0, 0, n, i, lmb, bit ^ 1);
			change(0, 0, n, lmb, lmb + 1, bit);
		}
		else
		{
			scanf("%d", &i);
			//printf("%d\n", i);
			ss[pn++] = getbit(0, 0, n, i) + '0';
			//printf("%c\n", ss[pn-1]);
		}
	}
	ss[pn] = 0;
	printf("%s\n", ss);
}

int main() {
	init();
	work();
}
                    


                        Solution in Java :

In  Java :








import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class ChangingBitsDataSet {
	
	private static int ADDRESS_BITS = 6;
	private static int MASK = (1 << ADDRESS_BITS) - 1;
	
	private static void setBit(long[] data, int index, int value) {
		int highi = index >>> ADDRESS_BITS;
		int lowi = index & MASK;
		long mask = 1L << lowi;
		if (value == 0) {
			data[highi] &= ~mask;
		}
		else {
			data[highi] |= mask;			
		}
	}
	
	private long[] a;
	private long[] b;
	private long[] sum;
	
	public ChangingBitsDataSet(int length, String aString, String bString) {
		a = new long[1 + (length >>> ADDRESS_BITS)];
		b = new long[1 + (length >>> ADDRESS_BITS)];
		sum = new long[1 + (length >>> ADDRESS_BITS)];
		int carryFlag = 0;
		for (int i = length - 1, bitIndex = 0; i >= 0; i--, bitIndex++) {
			int aBit = aString.charAt(i) - '0';
			int bBit = bString.charAt(i) - '0';
			int s = aBit + bBit + carryFlag;
			int sumBit = s & 1;
			carryFlag = (s & 2) >>> 1;
			setBit(a, bitIndex, aBit);
			setBit(b, bitIndex, bBit);
			setBit(sum, bitIndex, sumBit);
		}
		setBit(sum, length, carryFlag);
	}

	private void add(int index) {
		int highi = index >>> ADDRESS_BITS;
		int lowi = index & MASK;
		long block = sum[highi];
		if ((~block >>> lowi) == 0L) {
			block ^= -1L << lowi;
			sum[highi++] = block;
			while (sum[highi] == -1L) {
				sum[highi++] = 0L;
			}
			block = sum[highi];
			lowi = 0;
		}
		while (((block >>> lowi) & 1) == 1) {
			block ^= 1L << lowi;
			lowi++;
		}
		block ^= 1L << lowi;
		sum[highi] = block;
	}
	
	private void sub(int index) {
		int highi = index >>> ADDRESS_BITS;
		int lowi = index & MASK;
		long block = sum[highi];
		if ((block >>> lowi) == 0L) {
			block ^= -1L << lowi;
			sum[highi++] = block;
			while (sum[highi] == 0L) {
				sum[highi++] = -1L;
			}
			block = sum[highi];
			lowi = 0;
		}
		while (((block >>> lowi) & 1) == 0) {
			block ^= 1L << lowi;
			lowi++;
		}
		block ^= 1L << lowi;
		sum[highi] = block;
	}
	
	private void set(long[] data, int index, int value) {
		int highi = index >>> ADDRESS_BITS;
		int lowi = index & MASK;
		int oldValue = (int) (data[highi] >>> lowi) & 1;
		if (oldValue == 0 & value == 1) {
			data[highi] ^= 1L << lowi;
			add(index);
		}
		else if (oldValue == 1 & value == 0) {
			data[highi] ^= 1L << lowi;
			sub(index);
		}
	}
	
	public void setA(int index, int value) {
		set(a, index, value);
	}
	
	public void setB(int index, int value) {
		set(b, index, value);
	}
	
	public int getC(int index) {
		int highi = index >>> ADDRESS_BITS;
		int lowi = index & MASK;
		return (int)(sum[highi] >>> lowi) & 1;
	}
}

public class Solution {
	static private String OPERATION_SET_A = "set_a";
	static private String OPERATION_SET_B = "set_b";
	static private String OPERATION_GET_C = "get_c";
	
	static public void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 64 << 10);
			StringTokenizer tokenizer = new StringTokenizer(br.readLine());
			int n = Integer.parseInt(tokenizer.nextToken());
			int q = Integer.parseInt(tokenizer.nextToken());
			String a = br.readLine();
			String b = br.readLine();
			ChangingBitsDataSet dataset = new ChangingBitsDataSet(n, a, b);
			StringBuilder result = new StringBuilder(n);
			for (int i = 0; i < q; i++) {
				tokenizer = new StringTokenizer(br.readLine());
				String operation = tokenizer.nextToken();
				if (OPERATION_SET_A.equals(operation)) {
					dataset.setA(Integer.parseInt(tokenizer.nextToken()), Integer.parseInt(tokenizer.nextToken()));
				}
				else if (OPERATION_SET_B.equals(operation)){
					dataset.setB(Integer.parseInt(tokenizer.nextToken()), Integer.parseInt(tokenizer.nextToken()));					
				}
				else if (OPERATION_GET_C.equals(operation)){
					result.append(dataset.getC(Integer.parseInt(tokenizer.nextToken())));
				}
			}
			System.out.println(result);
		}
		catch (Exception e) {
			System.err.println("Error:" + e.getMessage());
		}
	}
}
                    


                        Solution in Python : 
                            
In  Python3 :








n_bit, line_count = [int(i) for i in input().split()]
a = int(input(), 2)
b = int(input(), 2)

for i in range(line_count):
    inp = input().split()
    x = int(inp[1])
    
    if inp[0] == "get_c":
        print(( (a+b) & (1 << x ) ) >> x, end="")
    
    elif inp[0] == "set_a":
        if inp[2] == "1":
            a = a | ( 1 << x )
        else:
            a = a & ~( 1 << x )
    
    else:
        if inp[2] == "1":
            b = b | ( 1 << x )
        else:
            b = b & ~( 1 << x )
                    


View More Similar Problems

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →