You are not logged in. Please login at www.codechef.com to post your questions!

×

Count of maximum-CHFMAX

What is wrong in this code

int main()
{

string str;

int arr[256]={0};

int t;

cin>>t;

for(int i=0;i<t;i++)

{
    cin>>str;

    for(int j=0;j<str.length();j++)
    {

        arr[str[j]]++;
    }
    int maxm=-1,pos=0;
                     char val;
                for(int m=0;m<256;m++)
                     {
                         if(arr[m]>=maxm&&arr[m]>0)
                         {
                             if(arr[m]==maxm)
                             {
                                 if(m>pos)
                                    maxm=arr[pos];

                             }
                             else
                             {
                                 maxm=arr[m];
                                 pos=m;
                             }
                         }



                }
           for(int j=0;j<256;j++)
            {


                if(arr[j]==maxm)
                {val=j;
                break;
            }}

    for(int i=0;i<str.length();i++)
    {

        if(str[i]==val)
            str[i]='?';
    }
    cout<<str<<endl;
    }
    return 0;
}

asked 20 Nov '14, 17:38

k_biplav's gravatar image

1★k_biplav
12
accept rate: 0%

edited 20 Nov '14, 19:06

betlista's gravatar image

3★betlista ♦♦
16.9k49115225


I think problem in you code is that you are not intialising array arr to 0 after every test case due to which previous frequencies of characters of old string are also getting added.

link

answered 20 Nov '14, 18:56

zealf's gravatar image

4★zealf
1.1k61126
accept rate: 3%

Declare int arr[256] = {0} inside for loop that is counting test case.
i.e

for(int i = 0; i < t;i++)
{
   int arr[256] = {0};
   //rest of the code..
}

This is because, if you do not initialise array values to zero for every test case, they take the values that remained in the array after previous test case. So count of frequency of characters differ.

Ex : let this be input

2
aba
abcd

With your code, frequencies of characters in second test case would give a = 3, b = 2, c = 1, d = 1.

link

answered 20 Nov '14, 18:59

vinayawsm's gravatar image

4★vinayawsm
1.9k21430
accept rate: 24%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×2,476
×1,919
×856

question asked: 20 Nov '14, 17:38

question was seen: 1,169 times

last updated: 20 Nov '14, 19:06