Problem Link
#include<iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int freq[26];
int main()
{
int t, len, maxFreq, diff, diffa, diffb, ans;
string s;
cin >> t;
while(t--)
{
cin >> s;
memset(freq, 0, sizeof(freq));
len = s.length();
for(int i = 0; i < len; i++)
{
freq[s[i] - 'A']++;
}
sort(freq, freq + 26, greater<int>());
ans = len;
for(int i = 1; i <= 26; i++)
{
if(len % i != 0)
continue;
maxFreq = len / i;
diffa = diffb = 0;
for(int j = 0; j < i; j++)
{
if(freq[j] == 0)
break;
diff = freq[j] - maxFreq;
if(diff > 0)
{
diffa += diff;
}
else
{
diffb -= diff;
}
}
ans = min(ans, max(diffa, diffb));
}
cout << ans << endl;
}
return 0;
}
#include<iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int freq[26];
int main()
{
int t, len, maxFreq, diff, diffa, diffb, ans;
string s;
cin >> t;
while(t--)
{
cin >> s;
memset(freq, 0, sizeof(freq));
len = s.length();
for(int i = 0; i < len; i++)
{
freq[s[i] - 'A']++;
}
sort(freq, freq + 26, greater<int>());
ans = len;
for(int i = 1; i <= 26; i++)
{
if(len % i != 0)
continue;
maxFreq = len / i;
diffa = diffb = 0;
for(int j = 0; j < i; j++)
{
if(freq[j] == 0)
break;
diff = freq[j] - maxFreq;
if(diff > 0)
{
diffa += diff;
}
else
{
diffb -= diff;
}
}
ans = min(ans, max(diffa, diffb));
}
cout << ans << endl;
}
return 0;
}
Comments
Post a Comment