Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:
- Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.
- Rearrange the letters of the found subsequence randomly and go to step 1.
Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.
Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.
The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string sonly contains characters: 'x', 'y', 'z'.
The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.
zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6
YES YES NO YES NO
In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.
题意:
按例子中算法运转,若能正确退出算法则输出“yes”,若无限循环则输出“NO”
想法:
对所给的例子找规律,可得所有能正常输出的例子x,y,z各自数量的差别<=1。
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int sum_x[100005],sum_y[100005],sum_z[100005];
int main()//sum_x[i]记录第1-i个数中x的数量
{
string a;
cin>>a;
int m;
cin>>m;
int sum_x_all=0,sum_y_all=0,sum_z_all=0;
for(int i=0;i<a.length();i++)
{
if(a[i]=='x')sum_x_all++;
if(a[i]=='y')sum_y_all++;
if(a[i]=='z')sum_z_all++;
sum_x[i]=sum_x_all;//sum_x_all作累加器,为sum_x[i]服务
sum_y[i]=sum_y_all;
sum_z[i]=sum_z_all;
}
int l,r;
for(int i=0;i<m;i++)
{
cin>>l>>r;
int x,y,z,flag=0;//x=所选片段中x的数量
x=sum_x[r-1]-sum_x[l-2];
y=sum_y[r-1]-sum_y[l-2];
z=sum_z[r-1]-sum_z[l-2];
if(fabs(x-y)<=1&&fabs(x-z)<=1&&fabs(y-z)<=1)flag=1;
if(r-l+1<3)flag=1;
if(flag)cout<<"YES"<<'\n';
else cout<<"NO"<<'\n';
}
}
/*注意点:即使复杂度相同,函数调用的形式处理后半段判断的过程会超时。*/