A.ABC String
problem
Chinese Language
This is just a translation of the main meaning
Example
input
4
AABBAC
CACA
BBBBAC
ABCA
output
YES
YES
NO
NO
Note
In the first testcase one of the possible strings b is “(())()”.
In the second testcase one of the possible strings b is “()()”.
Code and Analysis
#include<iostream>
using namespace std;
string s;
int n;
bool ans=false;
int st[3]={0,-1,1};//Let the closing bracket be -1 and the opening bracket be 1
int box[5],vis[5];
//Judging the type of brackets represented by each ABC
bool check(int a,int b,int c)
{
int x=0;
for(int i=0;i<n;i++)
{
if(s[i]=='A') x+=a;
if(s[i]=='B') x+=b;
if(s[i]=='C') x+=c;
if(x<0)return false;
}
return x==0? true:false;
}
//Traverse all combinations of ABC
void recursion(int flag)
{
if(flag>3)
{
if(check(box[1],box[2],box[3]))
{
ans=true;
}
return ;
}
for(int i=1;i<=2;i++)
{
if(vis[flag]==0)
{
box[flag]=st[i];
vis[flag]=1;
recursion(flag+1);
vis[flag]=0;
}
}
}
int main()
{
int T ;
cin>>T ;
while(T--)
{
ans=false;
cin>>s;
n=s.length();
recursion(1);
if(ans)cout<<"YES"<<'\n';
else cout<<"NO"<<'\n';
}
return 0;
}
If the previous code is a bit difficult to understand, you can look at the following code
#include<iostream>
std::string s;
int n;
bool check(int a, int b, int c){
int x = 0;
for(int i=0;i<n; i++){
if(s[i] == 'A'){
x += a;
}
if(s[i] == 'B'){
x += b;
}
if(s[i] == 'C'){
x += c;
}
if (x<0){
return false;
}
}
return x == 0;//'==' means judgment here.
//Returns true if the judgment result is true, otherwise returns false
}
int main()
{
int T;
std :: cin>>T;
for(int cas =1; cas<=T; cas++){
std::cin>>s ;
n = s.length();
bool ans = false ;
for(int a =-1; a<= 1; a+=2)
for(int b=-1; b<=1;b+=2)
for(int c=-1; c<=1; c+=2)
if(check(a,b,c)){
ans = true;
goto flag;
}
flag:;
std::cout<< (ans ? "YES\n" : "NO\n");
}
return 0;
}