Buy 1-Get 1 Wrong answer...!!!

http://www.codechef.com/problems/BUY1GET1
Above is the probelm of codechef, i tried to solve. I wrote the following code running perfectly fine on my laptop. Tried hard, but can’t find any eroor for many other test cases also. Please Help.

My Algorithm - Declaring variables and an array as a count for 52 characters as mentioned i.e. 0-25 for upper case and 26-51 for lower case alphabets. Then, taking the no. of test cases. Then, using a loop to get string as a sequence of character until a newline is encountered. Now, using ASCII value of character of string, incrementing corresponding element of array.
After this, calculating and printing the cost for each string using another loop and resetting the values of array elements.

Here is my source code(written in C):

#include <stdio.h>

int main(){
  int test,money,i,num[52] = {0};
  char ch = '1';
  scanf("%d",&test);
  getchar();
  while(test--){
    money = 0;
    while(ch!='\n'){
      scanf("%c", &ch);
      if((int)ch>91)
	num[(int)ch-71]++;
      else
	num[(int)ch-65]++;
    }
    ch = '1';
    for(i=0;i<52;i++){
      money += num[i]/2 + num[i]%2;
      num[i] = 0;
    }
    printf("%d\n", money);
  }
  return 0;
}

Ur answer is correct, with only one problem that u r detecting ‘\n’ for a next line… consider the last test case in input… according to ur program it is important that there must be a next line character, but the last case will not have it…

for extreme case purpose I tested ur solution… do notice that for same input it is responding differently as first I didnt gave a newline character and then I gave newline character… for more reference u can refer my solution

2 Likes

Hey thanks buddy…as you pointed out i made a small modification in my my previous code…Now, using while loop i take the characters of string until a non-alphabetic character is encountered. But, this is also not working. I have seen that many have done this using string, but i want to do it my way. Can you help me out this time.

Revised Source Code

#include <stdio.h>

int main(){
  int test,money,i,num[52] = {0};
  char ch;
  scanf("%d",&test);
  getchar();
  while(test--){
    ch = 'a';
    money = 0;
    while((ch>64 && ch<91) || (ch>96 && ch<123)){
      scanf("%c", &ch);
      if(ch>91)
	num[ch-71]++;
      else
	num[ch-65]++;
    }
    ch = '1';
    for(i=0;i<52;i++){
      money += num[i]/2 + num[i]%2;
      num[i] = 0;
    }
    printf("%d\n", money);
  }
  return 0;
}

See your code is correct, the only probable problem I found is of scanning input… and the same problem exist with your Revised code… It will be better to use string input by taking an array of required size… there is no probable logic error, its just input problem which I mentioned before… I don’t have strong C/C++ background and I usually code in Python… so I can’t help you more into this… :frowning:

ok thanx yaar…!!!

//