WA in SPOJ HC

, ,

I was trying to solve the problem HAPPY COINS on spoj. spoj.pl/problems/HC
I first tried to write this code but i don’t know why it takes only one input

#include<stdio.h>
#include<string.h>
int main()
{
long int t,i,n,count=0;
char s[3],a[]="lxh";
scanf("%ld",&t);
while(t--)
{
    count=0;
    scanf("%ld",&n);
    while(n--)
    {
        scanf("%s",s);
        if(strcmp(s,a)==0)
            count++;
    }
    if(count%2==0)
        printf("hhb\n");
    else
        printf("lxh\n");

}
return 0;

}

then i increased the size of sting s to 4 and when i submitted it, i got AC.

#include<stdio.h>
#include<string.h>
int main()
{
long int t,i,n,count=0;
char s[4],a[]="lxh";
scanf("%ld",&t);
while(t--)
{
    count=0;
    scanf("%ld",&n);
    while(n--)
    {
        scanf("%s",s);
        if(strcmp(s,a)==0)
            count++;
    }
    if(count%2==0)
        printf("hhb\n");
    else
        printf("lxh\n");

}
return 0;

}

Please help me in understanding my mistake

In C a string is a contiguous sequence of characters terminated by and including the first null character (i.e. '\0'). So null character requires 1 byte space to store same as other characters.

Therefore in order to have string with 3 characters you should declare something like this

char s[4];

One byte extra space for null character. In above string characters will be stored as {'l','x','h','\0'}, {'h','h','b','\0'}. Hence your solution got AC in second case and WA in first one.

1 Like

thank you.

//