November Challenge Chef and Happiness

I’ve written the code for problem CHHAPPY. It should work fine. It runs under the given time limit but gives wrong answer for 3 out of 4 test cases. Please have a look at this code and lemme know what is the problem with this code…

My approach is that I make a structure array which is sorted version of A but with its initial indices attached with it. I also check which indices are present in A and mark them valid. Then I check under result function whether any 2 valid elements of structure are equal or not.

Here’s link to my code:
https://ideone.com/NFMTR9

1 Like

I’ve found the solution to my problem

bool result()
{
    for(int i=0;i<n;i++)
    {
        if(!str[i].valid)
            continue;
        ll j=i+1;
        while(str[i].val==str[j].val)
        {
            if(str[j].valid)
                return true;

            j++;
            if(j==n)
                break;
        }
    }
    return false;
}

Here, I was checking for valid numbers using a for loop which runs from 0 till n-1. But when I assign j=i+1, for the last index, it checks for the index n which should not be there. But for each test case, I was using the same structure array and overwrote the required part. Because of this, the data from the previous test case was compared in this case as well.

For example, for the test case

2
10
1 2 3 4 5 6 7 8 9 10
6
1 2 3 4 6 7

the output should be
Poor Chef
Poor Chef

but the output turns out to be

Poor Chef
Truly Happy

If you run the 2 test cases independently then you get the desired output.

This way, my code will give wrong answer in case of a coincidence, which happened to occur in 3 out of 4 test cases…

1 Like