【SSLGZ 2384】2014年初中竞赛试题(南海) 字符串
问题描述
小熊有一个由小写英文字母组成的字符串s = s1s2…sn。小熊想要计算s中有多少子串包含字符串“bear”,也就是找出满足字符串x(i, j)= sisi+1…sj 包含至少一个字符串“bear”的 (i, j)对数(1≤i≤j≤n)。
字符串x(i, j)包含字符串“bear”定义为存在一个整数k(i≤k≤j-3),满足sk=b,sk+1=e,sk+2=a,sk+3=r。
请帮助小熊解决这个问题。
输入
输入文件名为.in。
输入共1行,包含一个非空字符串s。数据保证字符串s中只包含小写英文字母。
输出文件名为.out。
输出共1行,包含一个整数,表示这个问题的答案。
样例输入
样例输出
算法讨论
很暴力的方法……基本等于一位位找再加点优化……效率很低。
constmaxn=3000;
vara:array[1..maxn,1..maxn] of longint;i,j,n,m,p,s:longint;f:boolean;st:ansistring;
beginassign(input,'string.in'); reset(input);assign(output,'string.out'); rewrite(output);readln(st);n:=length(st);m:=n;while st[m]<>'r' dodec(m);p:=1;while p<>m dobeginwhile st[p]<>'r' doinc(p);f:=true;for i:=1 to p-3 dobeginfor j:=p to n doif (st[p-3]='b') and (st[p-2]='e') and (st[p-1]='a') and (st[p]='r')then if a[i,j]=0then begininc(s);a[i,j]:=1endelseelse beginf:=false;breakend;if f=falsethen breakend;if p=mthen breakelse inc(p);end;write(s);close(input); close(output)
end.
Pixiv ID: