It works fine on my IDE. The link of the problem is Piece Of Cake
And here is my code----
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
int t,i,j;
double lenc;
cin>>t;
while(t--){
char s[1001];
//int cn[1001];
//memset(cn,0,sizeof(cn));
scanf("%s",s);
double len=strlen(s);
// sort(s,s+l);
int c,mc=0;
for(i=0;i<len;i++){
c=0;
for(j=0;j<len;j++){
if(s[j]==s[i]){
c++;
}
if(c>mc)
mc=c;
}
}
lenc=len/2;
if(mc==(lenc))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
Your algorithm looks correct. The only thing I see is you are comparing a double with an int and so maybe this is failing when the conversion is happening.
You don’t really need the double anyway. strlen() will always return an int and the answer is always NO if the len is odd. So
if (len % 2 == 0 && mc == len / 2) would be enough.
Note I haven’t confirmed this is your problem but this is all I can see.
See this line in problem statement
number of occurrences of some
character in the string is equal to
the sum of the numbers of occurrences
of other characters in the string
for example abc is the input then output should be ‘NO’ and your code prints ‘YES’
as number of occurences of ‘a’ is not equal to sum of occurences of ‘b’ and ‘c’ (that is rest of the characters)
The abc example does give the correct output with the listed code. The two for loops count up each char and set mc to the count of the most common character. Then lower down the code checks to see if mc is equal to half the length of the string, as the code is using doubles odd length strings will never match mc.
My above suggestion doesn’t fix your problem. Running your code seems to work on the simple test cases I tried as well.
Perhaps you could generate a lot of random strings and do a comparision between your code and a working solution and see if you can work out what the difference is. Here is my working solution if you want one to compare against. http://www.codechef.com/viewsolution/7279862
Finally worked out what the problem with the code was. It was frustrating me because your code looks correct. Comment out the following line and your solution will work.
//ios::sync_with_stdio(0);
Alternatively use cin instead of scanf. Basically if you are going to turn off syncing between C++ IO streams and C printf/scanf then don’t mix them. For more info look at this article
And thanks, I’ve learned something new about C++ answering your question.
2 Likes
Thanks and with your help I learnt something new too