Codeforces-> 1509B - TMT Document Solution in C++ with explanation .
1509B - TMT Document : https://codeforces.com/problemset/problem/1509/B
Code :
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define lg long long
#define fi(i,L,R) for (ll i = L ; i <= R ; i++)
#define fd(i,R,L) for (ll i = R ; i >= L ; i--)
#define s1 string
#define p_b push_back
#define st(n) sort(a,a+n)
#define rev reverse(a,a+n)
#define revs(j) reverse((j).begin(),(j).end())
#define srt(k) sort((k).begin(),(k).end())
#define suni s.erase(unique(s.begin(),s.end()),s.end())
#define vuni v.erase(unique( v.begin(),v.end()),v.end())
#define puni v1.erase(unique(v1.begin(),v1.end()),v1.end())
#define yo cout<<"YES"<<endl
#define no cout<<"NO"<<endl
#define M 1000000007
#define pie acos(-1.0)
#define pp endl
#define sz 200000
typedef pair<int, int> pi;
void Solve()
{
ll i,j,k,c=0,flag=0,c1=0,c2=0;
ll n; cin >>n;
s1 s; cin >>s;
map<char,ll>mp;
for(i=0;i<n;i++){
mp[s[i]]++;
}
c2=mp['T'],c1=mp['M'];
ll cnt=0;
for(i=0;i<n;i++){
if(c<0){
flag=1;
break;
}
else if(s[i]=='T') {
++c;
}
else{
--c;
}
}
revs(s);
for(i=0;i<n;i++){
if(cnt<0){
flag=1;
break;
}
if(s[i]=='T') cnt++;
else{
cnt--;
}
}
if(flag||c1*2!=c2||s[n-1]=='M') no;
else if(c==c1) yo;
else no;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int tt=1;
cin>>tt;
while(tt--)
{
Solve();
}
return 0;
}
Explanation : 1) Number of 'M'*2 must be equal to Number of 'T'. Else,No.
2) if counter is less than zero then answer is no.U have to check this from going forward to backward and backward to forward when iterating the string. That's why I reversed the string by using revs(s) function .
3) we will do increment for 'T' and decrement whenever we get 'M' and if the counter is equal to M after the iteration then its guaraanteed that T has covered all "M" s
Comments
Post a Comment