Wrong Answer
Code
#include <iostream>
#include <string.h>
using namespace std;
int t,n,f[1010],maxi,poz1,poz2;
char s[5010],r[5010],l,p;
int main()
{
cin>>t;
while (t)
{
t--;
cin>>s;
n=strlen(s);
for (int i=0; i<n; i++)
f[s[i]]++;
maxi=0;
p=NULL;
for (int i='a'; i<='z'; i++)
if (f[i]>maxi) { if (p==NULL) p=i; maxi=f[i],l=i;}
if (n%2==1 && maxi==n/2+n%2)
{
for (int i=1; i<=n; i=i+2)
r[i]=l;
f[l]=0;
}
else if (n%2==0 && maxi==n/2)
{
if (p==l)
{
for (int i=1; i<=n; i=i+2)
r[i]=l;
f[l]=0;
}
else
{
for (int i=2; i<=n; i=i+2)
r[i]=l;
f[l]=0;
}
}
if (maxi>n/2+n%2) cout<<-1;
else
{
poz1='a';
poz2='a';
for (int i=1; i<=n; i++)
if (r[i]==NULL)
{
while (!f[poz1]) poz1++;
while (!f[poz2]) poz2++;
if (poz1==poz2) poz2++;
while (!f[poz2]) poz2++;
if (i==1 || poz1!=r[i-1]) r[i]=poz1,f[poz1]--;
else if (poz2>'z')
{
for (int j=i-1; j>=1; j=j-2)
if (r[j]==poz1) swap(r[j],r[j-1]);
else break;
r[i]=poz1;
f[poz1]--;
}
else r[i]=poz2,f[poz2]--;
}
for (int i=1; i<=n; i++)
cout<<r[i];
}
cout<<'\n';
for (int i=1; i<=n; i++)
r[i]=NULL,s[i]=NULL;
for (int i='a'; i<='z'; i++)
f[i]=0;
}
return 0;
}
Information
- Submit By
- Type
- Submission
- Problem
- P1209 B. Rearrange the String
- Contest
- Educational Round 1
- Language
- C++17 (G++ 13.2.0)
- Submit At
- 2025-07-14 15:54:45
- Judged At
- 2025-07-14 15:54:45
- Judged By
- Score
- 0
- Total Time
- 2ms
- Peak Memory
- 560.0 KiB