CF 226 DIV2 B. Bear and Strings

来源:互联网 发布:阿里云计算概念股 编辑:程序博客网 时间:2024/05/16 10:12
B. Bear and Strings
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.

String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.

Help the bear cope with the given problem.

Input

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Output

Print a single number — the answer to the problem.

Sample test(s)
input
bearbtear
output
6
input
bearaabearc
output
20
Note

In the first sample, the following pairs (i, j) match: (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9).

In the second sample, the following pairs (i, j) match: (1,  4), (1,  5), (1,  6), (1,  7), (1,  8), (1,  9), (1,  10), (1,  11), (2,  10), (2,  11), (3,  10), (3,  11), (4,  10), (4,  11), (5,  10), (5,  11), (6,  10), (6,  11), (7,  10), (7,  11).

 

 

这题我一看最先想到的就是容斥,可惜自己对容斥不太熟悉,最后进入的死胡同

自己用容斥会错的原因:

A∪B∪C = A+B+C - A∩B - B∩C - C∩A +A∩B∩C

      我在做的是  C∩A 明显是没有减的

错误代码:

#include<stdio.h>#include<math.h>#include<string.h>#include<algorithm>#include<limits.h>using namespace std;int main(){char a[5555];int t[5555];//记录bear的位置while(scanf("%s",&a)!=EOF){int sum= 0; int l= strlen(a);for(int i= 0; i< l-3; i++)if(a[i]=='b'&&a[i+1]=='e'&&a[i+2]=='a'&&a[i+3]=='r'){sum++;t[sum]= i;}for(int i= 1; i<= sum; i++)printf("%d ",t[i]);printf("\n");__int64 ans= 0;for(int i= 1; i<= sum; i++){for(int j= 1; j+i-1<= sum; j++){__int64 be= t[j]+1;__int64 end= t[j+i-1] + 3;//if(i==2)//printf("%d %d\n",be,end);if(i%2){ans+= be*(l- end);//printf("%d %d %d\n",i,j,be*(l-end));printf("%d %d %d %d\n",i,be,l-end,ans);}else{ans-= be*(l- end);printf("%d %d %d %d\n",i,be,l-end,ans);}}}printf("%I64d\n",ans);}return 0;}


其实这题根本不要用到容斥,只要找出其中的规律即可

AC代码:

#include<stdio.h>#include<math.h>#include<string.h>#include<algorithm>#include<limits.h>using namespace std;int main(){char ch[5555];while(scanf("%s",&ch)!=EOF){int l= strlen(ch);int temp= 0;__int64 ans= 0;for(int i= 0; i< l-3; i++)if(ch[i]=='b'&&ch[i+1]=='e'&&ch[i+2]=='a'&&ch[i+3]=='r'){ans+= (i+ 1- temp) * (l- i -3);temp= i + 1;}printf("%I64d\n",ans);}return 0;}


 

0 0
原创粉丝点击