Oulipo
Description The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter 'e'. He was a member of the Oulipo group. A quote from the book:
Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of 500,000 consecutive 'T's is not unusual. And they never use spaces. So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet {'A', 'B', 'C', …, 'Z'} and two finite strings over that alphabet, a wordW and a text T, count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. Occurrences may overlap. Input The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:
Output For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T. Sample Input 3 BAPC BAPC AZA AZAZAZA VERDI AVERDXIVYERDIAN Sample Output 1 3 0 Source |
输入n组字符串s2和s1,问s1中s2出现了多少次。
简单KMP算法的应用。 KMP算法详解:http://www.matrix67.com/blog/archives/115
至于题目说不要用cin。。。我加优化后AC了 。
#include <iostream>
#include <string>
using namespace std;
string s1,s2;
int l1,l2,p[10010],i,j,n;
int main()
{
ios::sync_with_stdio(false);
cin>>n;
while (n--){
cin>>s2>>s1;
l1=s1.size();
l2=s2.size();
p[0]=-1; j=-1;
for (i=1;i<l2;++i){
while (j>-1 && s2[j+1]!=s2[i]) j=p[j];
if (s2[j+1]==s2[i]) ++j;
p[i]=j;
}
j=-1; int ans=0;
for (i=0;i<l1;++i){
while (j>-1 && s1[i]!=s2[j+1]) j=p[j];
if (s1[i] == s2[j+1]) ++j;
if (j+1==l2){
ans++;
}
}
cout<<ans<<endl;
}
return 0;
}
kdwycz的网站: http://kdwycz.com/
kdwyz的刷题空间:http://blog.csdn.net/kdwycz