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 word W 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 |
题意:
题目前面瞎扯半天。直接被我跳过。看了下输出和后半部分的描述。就是给你一个子串w再给你一个文本串t问你子串在文本串中出现的次数。
思路:
KMP裸题。
详细见代码:
#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
char txt[1000100],word[10010];
int f[10010],ans;
void getf(char *p)//得到失配数组
{
int i,j,m=strlen(p);
f[0]=f[1]=0;
for(i=1;i<m;i++)
{
j=f[i];
while(j&&p[j]!=p[i])
j=f[j];
f[i+1]=p[j]==p[i]?j+1:0;
}
}
void finds(char *T,char *p)//T为文本串。P为模式串。
{
int i,j,n=strlen(T),m=strlen(p);
getf(p);
for(i=0,j=0;i<n;i++)
{
while(j&&p[j]!=T[i])
j=f[j];
if(p[j]==T[i])
j++;
if(j==m)
{
ans++;
j=f[j];//注意这里
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",word,txt);
ans=0;
finds(txt,word);
printf("%d\n",ans);
}
return 0;
}
写完直接1A正好0点。感觉不错。KMP很有意思。算懂一点点了吧。