COOMILK - Editorial

PROBLEM LINK:

Practice
Contest

Author: Kamil Debowski
Tester: Niyaz Nigmatullin
Editorialist: Kamil Debowski

DIFFICULTY:

CAKEWALK

PREREQUISITES:

none

PROBLEM

Given a sequence of strings “cookie” and “milk”, you should check whether after each “cookie” the next string is “milk”.

EXPLANATION

We should implement exactly what is written in the statement.
For each string s[i] if it is “cookie” then we must check if s[i+1] is “milk”.
So the answer will be “NO” in two cases (assuming that s[i] == “cookie”):

  1. i = N, what means that s[i] is the last string
  2. s[i+1] == "cookie"

Let’s see the pseudocode of this intended solution:

bool answer = true
for i = 1 to N do
	if (s[i] == "cookie") then
		if (i == N or s[i+1] != "milk") then
			answer = false
if (answer) then
	print("YES")
else
	print("NO")

POSSIBLE MISTAKES

One wrong approach is to think that the answer is “NO” if and only if some two consecutive strings are both equal to “cookie”.
For example, (“milk”, “cookie”, “cookie”, “milk”) indeed gives answer “NO”.
The last of given in the statement example test cases shows that this claim isn’t correct.
The answer is “NO” also if the last string is “cookie”.
In such a situation Limak indeed eats a cookie and doesn’t drink milk in the next minute.

ALTERNATIVE APPROACH

A mistake described in the previous paragraph can be fixed by additionally checking the last string of the given sequence.
So we can get a slightly different implementation:

bool answer = true
for i = 1 to N-1 do   #we iterate to N-1 only!
	if (s[i] == "cookie" and s[i+1] == "cookie") then
		answer = false
if (s[N] == "cookie") then
	answer = false

AUTHOR’S AND TESTER’S SOLUTIONS:

Setter’s solution can be found here.
Tester’s solution can be found here.

3 Likes

Can someone explain why my code is giving WA in both the test cases? I implemented the exact solution as ERRICHTO explained in his alternative solution.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.stream.*;
import java.util.Map.*;

/* 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 {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());

        while (t-- > 0) {
            int n = Integer.parseInt(br.readLine());
            String[] s = br.readLine().split(" ");
            
            boolean flag = true;
            if(s[s.length - 1].equals("cookie")){
                flag = false;
            } else {
                for(int i = 0; i < s.length - 1; i++){
                    if (s[i].equals("cookie") && s[i + 1].equals("cookie")) {
                        flag = false;
                        break;
                    }
                }
            }
            System.out.println(flag ? "yes" : "no");
            
        } // while
    }// main
}// CODECHEF //