TWTCLOSE - Editorial

array-string
cakewalk
cook23
editorial

#1

PROBLEM LINKS:

[Practice][1] [Contest][2]

DIFFICULTY

Cakewalk

PREREQUISITES

Basic string reading, using array

PROBLEM

The problem essentially is to maintain binary (open(1) or close(0)) state of N tweets and simulate K actions on them. The two types of actions are (a) CLICK X , which toggles the state of Xth tweet and (b) CLOSEALL , which sets the state of all the N tweets to close(0). After each of the K actions given, we need to find the total number tweets in open(1) state.

EXPLANATION

If you are beginner in programming contests, note that its common to assume that 108 basic arithmetic operations are performed in 1 second on modern computers. It may actually be faster than this (roughly 109 operations per second) on your computer. This is not always guaranteed as it may depend on several other factors. Some of them are handling heavy input/output, using modulo operator a lot, using long or double operands etc. So its always good to try a few practice problems in a site, for better estimation of actual run times.

For this problem, first lets look at a very naive approach, which is fast enough for the given constraints N ≤ 1000 and K ≤ 1000. We need to maintain the current state (isOpen) of N tweets, for which we can simply use an array of booleans (true/false) or integers (1/0). CLICK X toggles the state of Xth tweet, so if isOpen[X] == 1 then set isOpen[X] = 0, else if isOpen[X] == 0 then set isOpen[X] = 1. This can be done using a single statement isOpen[X] = 1 - isOpen[X] or using xor(^) operator, isOpen[X]^=1. CLOSEALL sets the state isOpen[X] = 0, for all the tweets X = 1 to N. To find the number of opened tweets at any time we can simply traverse the state array and count the number of opened tweets. This method requires O(N) memory, O(1) time for toggle, O(N) time for each CLOSEALL and O(N) time to find number of opened tweets. Overall for K operations it has worst case time of O(NK), which is fast enough for the given constraints.

SETTER'S SOLUTION

Can be found [here][3]

APPROACH

The problem setter used the above approach to solve the problem. For comparing two strings, the inbuilt function [strcmp][4] in string library is used.

TESTER'S SOLUTION

Can be found [here][5]

APPROACH

Note that we don’t need to run a O(N) loop each time we want the count of opened tweets. The number of opened tweets changes by only either +1 or -1 with each CLICK X. So if the state of Xth tweet changes from close to open, we add 1, else if it changes from open to close, we subtract 1. So we can have this count in O(1) time per CLICK. Note that CLOSEALL still requires to reset all the states to 0 and is O(N). The overall solution if still O(NK) worst case time. Refer tester’s solution for this approach.

EXERCISE

  1. Can you solve this problem in O(K) time using O(N) memory ? meaning, constant time for each CLICK and each CLOSEALL. Think about it and write your ideas in comments below.

#2

Cant we use memset function for making all the values to 0( when we get CLOSEALL ) . i think this will take less than O(N) time.


#3

Here I present some way how to do all in O(K) time and O(N) memory.

Note however that complexity of dealing with each particular CLOSEALL query can be not O(1).

Additionally to approach described in the editorial you just need to save in some stack all tweets that were clicked. Once we have CLOSEALL query we pop each tweet from the stack and set isOpen[X] to 0, where X is the current tweet. Note that for some X we can have already isOpen[X] == 0 if it was clicked several times but we don’t care about that. After this loop we will have empty stack and can continue to handle queries one by one.

This approach has complexity O(K) since we analyze each click at most twice: one time when we deal with actual query of this click and second time for the first CLOSEALL query after this click. This is a so-called amortized analyses - very useful logic that anyone should learn.


#4

And now let’s discuss actual solution to the exercise where each query performed in O(1) time.

At first we numerate all queries starting from 1.

Next let’s modify a bit our array isOpen[] and store the following information there:
isOpen[X] = 0 if tweet X is closed, otherwise isOpen[X] is equal to the index of the last query where it was clicked. Further let’s num be a number of currently open tweets (as in tester solution). Finally we also need additional variable last which is equal to the index of the last CLOSEALL query.

Initially last, num and isOpen[X] for all X are zeros.

Now suppose we have query CLICK X with index i. If isOpen[X] == 0 then we simply set isOpen[X] = i and add 1 to num. If isOpen[X] = j where j is not zero then situation is a bit trickier. At first we check whether j < last. If so then it means that in fact tweet X was closed during query CLOSEALL with index last after it was clicked last time and hence at first we should set isOpen[X] to 0 and then proceed as in the previous case. On the other hand if j > last then this tweet is actually opened and hence we should close it. That is, we need to set isOpen[X] = 0 and to decrease num by 1. Thus, we consider all possible cases for CLICK query. Note that we can combine first and second case in one case by condition isOpen[X] <= last. Indeed if isOpen[X] == 0 then it is always <= last.

If we have CLOSEALL query then we simply set last = i and num = 0.

It is easy to see after each query num is the correct number of opened tweets.
Also now it is straightforward that each query is performed in O(1) time.

You can check this solution as a reference for this approach.


#5

Here’s an alternate solution in O(Q) which is easier to understand:-

Q= no of queries

each time we have a click we add the element clicked to our click list, if an element is even no of times in our clicklist it means it is closed.

now when we have a close all query, we

1)decrease the opencount to 0

  1. for all clicked elements, unclick them(we find the clicked elements by traversing the clicklist)

  2. decrease the listCtr to 0

since each click is used only once while clicking and second while unclicking (during CLOSEALL) the net solution is
O(no of clicks)= O(Q)
link= solution


#6

import java.util.Scanner;
class twt
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int n,k,i,j,c,p;
String x ;
String y;

	n = s.nextInt();
	k = s.nextInt();
	i = k;
	c = 0;
	int a[] = new int[1002];
	while(true)
		{
		
		
		i--;
		x = s.next();
		
		
		if(x.equals("CLOSEALL"))
			{
			c = 0;
			System.out.println(c);
			for(p=0;p<n;p++)
			a[p]=0;
			}
		else
			{
				y = s.next();
				j = Integer.parseInt(y);
				if(a[j]==0)
				{
				a[j]++;
				c++;
				System.out.println(c);
				}
				else
				{	
				a[j]--;
				c--;	
				System.out.println(c);
				}
			}	
		if(i==0)
		break;
		}
		}
	}

I M NOT ABLE TO FIND OUT WAT IS WRONG IN MY SOLUTION…PLZ HELP.


#7

#include
#include
#include
using namespace std;
int main()
{
int n,k;
string str;
cin>>n>>k;
bitset<1000>status(0);
getline(cin,str);
while(k–)
{
getline(cin,str);
if(str == “CLOSEALL”)
status.reset();

		else
			status.flip(str[6]-1-48);

		cout<<status.count()<<endl;
	}
	return 0;
}

What’s wrong???


#8

public class tweet {

    public static void main(String[] args) throws java.io.IOException {
        java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        String[] t = r.readLine().split(" ");

        int N = Integer.parseInt(t[0]);
        int K = Integer.parseInt(t[1]);

        boolean arr[] = new boolean[N];

        java.util.Arrays.fill(arr, false);
        int count = 0;
        for (int i = 0; i < K; i++) {
            String t1 = r.readLine();
            int n = t1.length();

            char a = t1.charAt(n - 1);

            if (a == 'L') {
                java.util.Arrays.fill(arr, false);
                count = 0;
                System.out.println(count);
            } else {
                int c = Integer.parseInt(t1.substring(n - 1, n));
                c = c - 1;
                if (arr[c] ) {
                    arr[c] = false;
                    count--;
                } else {
                    arr[c] = true;
                    count++;
                }
                System.out.println(count);
            }

        }
    }
}

Why am i getting NZEC in this solution ? Can anyone help me out ?


#9

Im getting NZEC with the following code… although sample input works fine…
smone please help me out… i’m new


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Main {

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

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String[] input = br.readLine().split("\s");

int N = Integer.parseInt(input[0]);

int k = Integer.parseInt(input[1]);

String str;
int open=0;

int arr[]=new int[1000];

while(k!=0){

String[] input1 = br.readLine().split("\s");

if (input1[0].equals("CLOSEALL"))
{   open=0;
    System.out.println(open);
    
    for(int i=0;i<arr.length;i++)
        arr*=0;
        
        }

else if (arr[Integer.parseInt(input1[1])]==1)
{
    arr[Integer.parseInt(input1[1])]=0;
    open--;
    System.out.println(open);
}

else 
{ open++;
 arr[Integer.parseInt(input1[1])]=1;
    System.out.println(open);
}

k--;

}}}


#10

Please find the error in this solution :

My Solution :slight_smile: Thanks in advance!


#11

#include<string.h>
#include<stdlib.h>
void main()
{
int t,n,p,q,i,j,k,x;
char a[8];
scanf("%d %d",&t,&n);
p=(int
)calloc(t,sizeof(int));
q=(int
)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
k=0;
scanf("%s",a);
if(strcmp(a,“CLICK”)==0)
{
scanf("%d",&x);
if(p[x-1]==1)
p[x-1]=0;
else
p[x-1]=1;
}
else{
for(j=0;j<t;j++)
p[j]=0;}
for(j=0;j<t;j++)
if(p[j]==1)
k++;
q*=k;
}
for(i=0;i<n;i++)
printf("%d
",q*);
}

Is there any error in my code???
It works fine when i run it in my system but it is giving a runtime error when i submit it!! :confused:


#12

import java.io.*;
import java.util.ArrayList;
class TWTCLOSE{
public static void main(String args[])throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out, true);
String str[] = br.readLine().split(" “);
ArrayList al = new ArrayList(),ans = new ArrayList();
int tweets = Integer.parseInt(str[0]);
int clicks = Integer.parseInt(str[1]);
while(clicks–>0){
int twtnum;
String twtstr[] = br.readLine().split(” ");
if(!“CLOSEALL”.equals(twtstr[0])){
twtnum = Integer.parseInt(twtstr[1]);
if(al.contains(twtnum))
al.remove(twtnum);
else
al.add(twtnum);
}
else
al.clear();
ans.add(al.size());
}
for(int a:ans)
pw.println(a);
}
}


#13

https://www.codechef.com/viewsolution/8138468
Please have a look at the above link. I need some help. What I did?
I simply calculated the length of the choice-“7 for CLICK X” otherwise “CLOSEALL”.
If len==7,then I just checked choice[6] what is it’s numeric value.To calculate the numeric value I simply did this: choice[6]-‘0’. But it showed wrong answer. I will be thankful to anyone who will take some patience and will help me for this. I will learn something which I should have known till now. Thank You. :slight_smile:


#14

i cant find out my mistake…can anyone help me…

#include<stdio.h>
#include<string.h>
#include<assert.h>

 void closeAll(int t[],int n)
{
int i;
 for(i=0;i<=n;i++)
{
	t*=0;
}
printf("%d

",countOpen(t,n));
}

   void toggle(int t[],int pos,int n)
  {
  if(t[pos]==0)
	t[pos]=1;
else
	t[pos]=0;
	
printf("%d

",countOpen(t,n));
}
int countOpen(int t[],int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(t*==1)
count++;
}

return count;
   }
   int main()
   {
int t[1000]={0},n,k,x=0;
char operation[10];
scanf("%d",&n);
assert(n>0&& n<1001);
scanf("%d",&k);
assert(k>0&&k<1001);
while(k){
						scanf("%s",operation);
						if(strcmp("CLICK",operation)==0)
						{
							scanf("%d",&x);
							//printf("val x=%d",x);
							assert(x>0&&x<=n);
							toggle(t,x,n);
						}
						else
							closeAll(t,n);
					k--;
				}





return 0;

}


#15

please help me out in this problem name “Closing the Tweets”. I am getting wrong output error for my solution


#16

I have used a Set for inserting and deleting of elements which requires O(logN) for both operations and clear for closing all the tweets, which takes O(N) hence, overall it took O(NK) time. Even though my solution got AC in 0.0 seconds, still O(NK) is more for this problem right?


#17

On what test case this code fails?

include

int main() { int n,k,i; scanf("%d %d",&n,&k); char s[10]; int a[n]; for(i=0;i<n;i++) a*=0;

while(k--){ int flag=0,y=0,m,num=0; scanf (" %[^ ]%c",s); for(i=6;s*!='\0';i++) { m=s*-'0'; num=num10+m; }

if(num>=1 && num<=n) { if(a[num-1]==0) a[num-1]=1; else a[num-1]=0; } else{ y=0; flag=1; }

if(flag==0){ for(i=0;i<n;i++) { if(a*==1) y++; } } printf("%d ",y); } }


#18

Link to my solution :

https://www.codechef.com/viewsolution/7286581


#19

Why is this problem placed among medium difficulty problems? It looks trivial to me and should belong to the beginner problems.


#20

#include
#include
using namespace std;

int change(int* arr, char c,int n)
{
int sum=0;
arr[int©-49]=(arr[int©-49])?0:1;
for(int i=0;i<n;i++)
sum+=arr*;

return sum;

}

int main()
{
int n,k;
string s1,s2;
char c;
cin>>n>>k;
int arr[n];
for(int j=0;j<n;j++)
arr[j]=0;

for(int i=0;i<k;i++)
{
	cin>>s1;
	if(s1=="CLICK")
	{
		cin>>s2;
		c=s2.at(0);		
		cout<<change(arr,c,n)<<"

";
}
if(s1==“CLOSEALL”)
{
for(int j=0;j<n;j++)
arr[j]=0;
cout<<"0
";
}
}
}

Why am I getting wrong answer?