Educational Codeforces Round 105 (div 2) A
A. ABC String
原题链接
题面
You are given a string a, consisting of n characters, n is even. For each i from 1 to n ai is one of ‘A’, ‘B’ or ‘C’.
A bracket sequence is a string containing only characters “(” and “)”. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters “1” and “+” between the original characters of the sequence. For example, bracket sequences “()()” and “(())” are regular (the resulting expressions are: “(1)+(1)” and “((1+1)+1)”), and “)(”, “(” and “)” are not.
You want to find a string b that consists of n characters such that:
b is a regular bracket sequence;
if for some i and j (1≤i,j≤n) ai=aj, then bi=bj.
In other words, you want to replace all occurrences of ‘A’ with the same type of bracket, then all occurrences of ‘B’ with the same type of bracket and all occurrences of ‘C’ with the same type of bracket.
Your task is to determine if such a string b exists.
Input
The first line contains a single integer t (1≤t≤1000) — the number of testcases.
Then the descriptions of t testcases follow.
The only line of each testcase contains a string a. a consists only of uppercase letters ‘A’, ‘B’ and ‘C’. Let n be the length of a. It is guaranteed that n is even and 2≤n≤50.
Output
For each testcase print “YES” if there exists such a string b that:
1、b is a regular bracket sequence;
2、if for some i and j (1≤i,j≤n) ai=aj, then bi=bj.
Otherwise, print “NO”.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
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 "()()".
题意
将所给的字母替换成"(“或”)",并且相同种类的字母只能替换成相同种类的括号,从而使得替换后的括号字符串中的所有"("(或")")都有唯一的")"(或"(")与之对应。
思路
从题意中可以看出,每一个符合的括号字符串都满足首位为"(“末位为”)"的情况,从中我们就可以确定两种字母所替换的括号类型,最后一种字母则可以分两种情况讨论了,具体操作请看代码。
代码如下
#include <iostream>
using namespace std;
string a;
int sum1,sum2;
int flag1,flag2;
int main(void)
{
int t;
cin >> t;
while(t--)
{
flag1 = flag2 = 1;
cin >> a;
sum1 = sum2 = 0;//sum1,sum2分别记录两种情况中"("剩余数目
int num = a.size()-1;//num表示末位
if(a.size()%2==0){
if(a[0] == a[num]){
cout << "NO" <<endl;//首末相等一定不成立
}else {
for(int i=0;i<a.size();i++)
{
if(a[i] == a[0]){//找到"("则加一
sum1++;
sum2++;
}else if(a[i] == a[num]){//找到")"则减一
sum1--;
sum2--;
}else {
sum1++;//第三种为"("时
sum2--;//第三种为")"时
}
if(sum1<0)flag1 = 0;
if(sum2<0)flag2 = 0;
//当发现"("数目为负数时表示")"多余,一定不会成立
}
if(flag1&&sum1)flag1 = 0;
if(flag2&&sum2)flag2 = 0;
if(flag1||flag2)cout << "YES" << endl;
else cout << "NO" << endl;
}
}else {
cout << "NO" << endl;
}
}
return 0;
}