【题解】CF1606A AB Balance

· · 题解

【原题链接】

一道 nt 题居然想了我十几分钟

题目分析

不难发现,只有在连续的 ab 之间才会产生 abba

下文中用 (a) 表示连续的 a(b) 表示连续的 b

由于字符串一定是类似于 (a)(b)(a)... 的样子,所以 \mathrm{AB}(s)\mathrm{BA}(s) 一定是相等或者只相差 1

考虑一下 \mathrm{AB}(s)>\mathrm{BA}(s) 的情况:

\mathrm{BA}(s)>\mathrm{AB}(s) 时也是类似的。

代码实现

#include <bits/stdc++.h>
using namespace std;

/*
省略快读快写模板
*/

int T,n,ab,ba;
char s[105];
int main()
{
    qin>>T;
    while(T--)
    {
        qin>>s+1,n=strlen(s+1);
        ab=ba=0;
        for(int i=1;i<n;i++)
        {
            if(s[i]=='a' && s[i+1]=='b')    ab++;
            if(s[i]=='b' && s[i+1]=='a')    ba++;
        }
        if(ab>ba)   s[n]='a';
        if(ab<ba)   s[n]='b';
        qout.writeln(s+1);
    }
//  return qout.flush(),0;
}