CF1509B TMT Document 题解
题目翻译:给出一个序列,只包含 T
和 M
,问是否能将这个字符串分割成若干个不重合的字串,让每个串都是 TMT
。
我们发现当且仅当满足一下条件的序列才可能是满足题意的:
T
的数量是M
的数量的两倍- 对于每个字符串的前缀,
T
的数量一定大于等于M
的数量 - 对于每个字符串的后缀,
T
的数量一定大于等于M
的数量
我们只需要检验每个前缀和后缀就可以了,也就是扫两次,算法复杂度 \(O\left(N\right)\)
代码:
#include<cstdio>
#include<iostream>
#define maxn 100039
using namespace std;
//#define debug
typedef int Type;
inline Type read(){
Type sum=0;
int flag=0;
char c=getchar();
while((c<'0'||c>'9')&&c!='-') c=getchar();
if(c=='-') c=getchar(),flag=1;
while('0'<=c&&c<='9'){
sum=(sum<<1)+(sum<<3)+(c^48);
c=getchar();
}
if(flag) return -sum;
return sum;
}
char s[maxn];
int T,n;
int check1(){
int cnt1,cnt2;
cnt1=cnt2=0;
for(int i=1;i<=n;i++)
if(s[i]=='T')
cnt1++;
else{
cnt2++;
if(cnt1<cnt2) return 0;
}
if(cnt1==cnt2*2) return 1;
else return 0;
}
int check2(){
int cnt1,cnt2;
cnt1=cnt2=0;
for(int i=n;i>=1;i--)
if(s[i]=='T')
cnt1++;
else{
cnt2++;
if(cnt1<cnt2) return 0;
}
return 1;
}
int main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
T=read();
while(T--){
n=read();
scanf("%s",s+1);
if(check1()&&check2()) puts("YES");
else puts("NO");
}
return 0;
}