Getting wrong answer for ADACRA. Here's my C code.

#include <stdio.h>
#define max(a, b) ((a) > (b)) ? (a):(b)

int main(void) {
int t;
scanf("%d", &t);
while(t--){
int n, flag;
scanf("%d", &n);
char s[51];
scanf("%s", s);
int i;
int uc = 0, dc = 0;
for(i = 0; i < n; i++){
    if(s[i] == 'U'){
        if(flag == 1){
            uc++;
            flag = 0;
        } else {
            flag = 0;
        }
    } else {
        if(flag == 0){
            dc++;
            flag = 1;
        } else {
            flag = 1;
        }
    }
}

int result = max(uc, dc);
if(uc == 0 || dc == 0) result = 0;
printf("%d\n", result);
}
return 0;

}

scanf("%d", &n);

This is wrong. The input gives the number of test cases, and then straightaway gives the strings. You need to do n=strlen(s) or any other function to get strings length. With no n in input, it gets assigned some garbage value which causes your for(i = 0; i < n; i++){ to malfunction.

Also, your flag variable is unintialised which leads to unexpected behaviour.

Buddy the problem in your code is that you have not initialised flag value and thus for the first time your code works well because it takes a garbage value for flag but consider this after execution of your first test case your flag value is set to 0 and in the second test case the input was say dduuddduuudd so your second else statement will increment dc but your logic didnt want that so thats the problem. you need to reset flag value each time the new test case enters as if it takes the default value 0 or 1 your logic is not gonna work.
hope this helps
happy coding.

Okay, I got it.
But about that flag variable, it works just fine nothing is wrong about it.
The problem was scanning variable ‘n’ unnecessarily. I used,
for(i = 0; s[i] != ‘\0’; i++)

I tried doing changes about that variable ‘n’, removed that scanf and used the s[i] != ‘\0’ condition, but still it says wrong answer.

Also, as “int flag;” is executed in each test case, so old flag variable memory is freed and new instance of variable flag is created.

Give it some initial value. If you just declare it, it CAN be allotted some random value like -10294329844 and it will give you output of 0 for that case, giving WA.

You will have to initialize flag according to the first character in string. OR calculate answer for both, if flag is initialised as 1 and again if its 0. Print the minimum of those.

exactly my point .
The garbage value can be 0 or 1 giving unexpected behavior

1 Like