TWTCLOSE - Editorial

PROBLEM LINKS:

Practice
Contest

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

APPROACH

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

TESTERā€™S SOLUTION

Can be found here

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.
3 Likes

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.

Memset would also take O(N) time to go through each element. But yes, the actual time might be lesser.
For every CLOSEALL, we do not do anything if number of tweets is 0. That could help but doesnā€™t lower worst case time.

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.

6 Likes

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 Likes

I used memset for filling 0s. My solution was showing wrong answer though I have implemented it same as mentioned in the tutorial.
http://www.codechef.com/viewsolution/1132512
Canā€™t find what is the difference :frowning:

@vikram535 : Please check the ā€˜memsetā€™ function in the library. The last parameter should be the number of bytes, and not number of elements in the array. If your array is int A[1001]; , you should use it as, memset(A,0,sizeof(A));

1 Like

You meant for example O(1/2 * N)? In fact that doesnā€™t matter, itā€™s asymptotically O(N).

Thank you so much for pointing out my mistake. I was not able to find it. Thanks again :slight_smile:

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

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.

here is counter example - http://ideone.com/A6o21

hey thnxā€¦my mistake i didnā€™t observe datā€¦thnx a lotā€¦

#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???

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 ?

Your class cannot be public, thatā€™s the first problem at CodeChef. In addition

int c = Integer.parseInt(t1.substring(n - 1, n));
c = c - 1;

smells - http://ideone.com/J3TYWf

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[i]=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--;

}}}

Please find the error in this solution :

My Solution :slight_smile: Thanks in advance!

@ajinkya1p3

You forgot to print number of open tweets after input ā€œCLOSEALLā€

I have added print statement and hereā€™s the accepted version of your code

http://www.codechef.com/viewsolution/5479172

1 Like

Thanks a lot!! :smiley: