题目链接:Codeforces 367A Sereja and Algorithm
看了人家的代码才写出来。。
这句话比较坑爹: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,
双重否定。。其实意思就是说如果可以通过变换得到一个串,它的任何三位连续数字串是这三个"zyx", "xzy", "yxz"中的一个,则算法终止,输出"YES"。
另外如果小于3个的话直接输出"YES"(不要问我为什么。。我也不知道)。
先预处理一下,遍历字符串,统计在s[i]之前的x的个数、y的个数和z的个数。之后用到哪个区间就把哪个的x、y、z的个数取出来在判断即可。
注意一下”YES“的条件:abs(x - y) <= 1 && abs(z - y) <= 1 && abs(z - x) <= 1,自己画画就看出来了(三个字母组成的串最多有六个,但是题目给的三种串已经可以表示全部了,剩下的三种是对称的,并不是所有的三个串都可以表示全部)。
non-zero probability是非零概率的意思。
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int MAX_N = 100000 + 1000;
char s[MAX_N];
int cnt_x[MAX_N],cnt_y[MAX_N],cnt_z[MAX_N];
int main()
{
cin >> s;
int len = strlen(s);
int x,y,z;
x = y = z = 0;
for(int i = 0;i < len;i++)
{
cnt_x[i] = cnt_y[i] = cnt_z[i] = 0;
if(s[i] == 'x')
x++;
else if(s[i] == 'y')
y++;
else if(s[i] == 'z')
z++;
cnt_x[i] = x;
cnt_y[i] = y;
cnt_z[i] = z;
}
int m,l,r;
cin >> m;
for(int i = 0;i < m;i++)
{
cin >> l >> r;
if(r - l + 1 < 3)
{
cout << "YES" << endl;
continue;
}
x = cnt_x[r - 1] - cnt_x[l - 2];
y = cnt_y[r - 1] - cnt_y[l - 2];
z = cnt_z[r - 1] - cnt_z[l - 2];
if(abs(x - y) <= 1 && abs(z - y) <= 1 && abs(z - x) <= 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}