Flipping Coins
Problem Statement :
There are N coins kept on the table, numbered from 0 to N - 1. Initially, each coin is kept tails up. You have to perform two types of operations: 1) Flip all coins numbered between A and B inclusive. This is represented by the command "0 A B" 2) Answer how many coins numbered between A and B inclusive are heads up. This is represented by the command "1 A B". Input : The first line contains two integers, N and Q. Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above. Output : Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query. Sample Input : 4 7 1 0 3 0 1 2 1 0 1 1 0 0 0 0 3 1 0 3 1 3 3 Sample Output : 0 1 0 2 1 Constraints : 1 <= N <= 100000 1 <= Q <= 100000 0 <= A <= B <= N - 1
Solution :
Solution in C :
#include <stdio.h>
#include <stdlib.h>
int t[20000002] = { 0 }, lz[20000002] = { 0 };
void update(int node, int s, int e, int l, int r) {
if (lz[node]) {
t[node] = (e - s + 1) - t[node];
if (s != e) {
lz[node << 1] ^= 1;
lz[(node << 1) | 1] ^= 1;
}
lz[node] = 0;
}
if (r < s || e < l || e < s)
return;
else if (l <= s && e <= r) {
t[node] = (e - s + 1) - t[node];
if (s != e) {
lz[node << 1] ^= 1;
lz[(node << 1) | 1] ^= 1;
}
return;
}
int m = s + (e - s) / 2;
update(node << 1, s, m, l, r);
update((node << 1) | 1, m + 1, e, l, r);
t[node] = t[node << 1] + t[(node << 1) | 1];
}
int query(int node, int s, int e, int l, int r) {
if (lz[node]) {
t[node] = (e - s + 1) - t[node];
if (s != e) {
lz[node << 1] ^= 1;
lz[(node << 1) | 1] ^= 1;
} lz[node] = 0;
}
if (r < s || e < l || e < s)
return 0;
else if (l <= s && e <= r)
return t[node];
int p, q, m = s + (e - s) / 2;
p = query(node << 1, s, m, l, r);
q = query((node << 1) | 1, m + 1, e, l, r);
return p + q;
}
int main() {
int n, q, t, a, b;
scanf("%d%d", &n, &q);
while (q--) {
scanf("%d%d%d", &t, &a, &b);
a++;
b++;
if (t) {
printf("%d\n", query(1, 1, n, a, b));
}
else {
update(1, 1, n, a, b);
}
}
return 0;
}
Solution in C++ :
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
ll seg[400010];
ll lazy[400010];
void up(int in,int l,int r,int sl,int sr)
{
if(lazy[in]!=0)
{
seg[in]=(sr-sl+1)-seg[in];
if(sl!=sr){
lazy[2*in]=!lazy[2*in];
lazy[2*in+1]=!lazy[2*in+1];
}
lazy[in]=0;
}
if(r<sl || l>sr || l>r)return;
if(sl>=l && sr<=r)
{
seg[in]=(sr-sl+1)-seg[in];
if(sl!=sr){
lazy[2*in]=!lazy[2*in];
lazy[2*in+1]=!lazy[2*in+1];
}
return;
}
int mid=sl+(sr-sl)/2;
up(in*2,l,r,sl,mid);
up(in*2+1,l,r,mid+1,sr);
seg[in]=seg[in*2]+seg[in*2+1];
}
ll sum(int in,int l,int r,int sl,int sr)
{
if(lazy[in]!=0)
{
seg[in]=(sr-sl+1)-seg[in];
if(sl!=sr){
lazy[2*in]=!lazy[2*in];
lazy[2*in+1]=!lazy[2*in+1];
}
lazy[in]=0;
}
if(r<sl || l>sr || l>r)return 0;
if(sl>=l && sr<=r)
return seg[in];
int mid=sl+(sr-sl)/2;
return sum(in*2,l,r,sl,mid) + sum(in*2+1,l,r,mid+1,sr);
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n,q;
cin>>n>>q;
while(q--)
{
int x,l,r;
cin>>x>>l>>r;
if(x==0)
up(1,l,r,0,n-1);
else{
cout<<sum(1,l,r,0,n-1)<<"\n";
}
}
}
Solution in Java :
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
InputStream inputStream=System.in;
InputReader sc = new InputReader(inputStream);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int q=sc.nextInt();
BitSet bs=new BitSet(n);
StringBuffer sb=new StringBuffer();
for(int i=0;i<q;i++)
{
int x=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
if(x==1)
{
sb.append(bs.get(a,b+1).cardinality()+"\n");
}
else
{
bs.flip(a,b+1);
}
}
System.out.println(sb.toString());
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
Solution in Python :
import numpy as np
n,q=map(int,input().split())
dp=np.zeros(n,dtype=bool)
while q>0:
zero,a,b=map(int,input().split())
if zero:print(np.count_nonzero(dp[a:b+1]))
else:dp[a:b+1]=~dp[a:b+1]
q-=1
View More Similar Problems
Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →