Description In the modern time, Search engine came into the life of everybody like Google, Baidu, etc. Input First line will contain one integer means how many cases will follow by. Output Print how many keywords are contained in the description. Sample Input
Sample Output
|
这道题完全套用模板,但是注意的是有可能有多个相同的模式串,算总和的时候都要算上。
#include<queue> #include<cstring> #include<cstdio> using namespace std; int ch[10002*52][26],End[10002*52],cur,fail[10002*52],last[10002*52],ans[10002]; char str[1000005],str0[10002][52]; int sum[10002*52]; void get_fail() { int now,tmpFail,Next; queue<int> q; for(int j=0; j<26; j++) { if(ch[0][j]) { q.push(ch[0][j]); fail[ch[0][j]] = 0; last[ch[0][j]] = 0; } } while(!q.empty()) { now = q.front(); q.pop(); for(int j=0; j<26; j++) { if(!ch[now][j]) continue; Next = ch[now][j]; q.push(Next); tmpFail = fail[now]; while(tmpFail&&!ch[tmpFail][j]) tmpFail = fail[tmpFail]; fail[Next] = ch[tmpFail][j]; last[Next] = End[fail[Next]] ? fail[Next]:last[fail[Next]]; } } } void Find () { int now = 0; int len = strlen(str); for(int i=0; i<len; i++) { if(str[i]<'a'||str[i]>'z') { now=0; continue; } str[i]-='a'; while(now&&!ch[now][str[i]]) now = fail[now]; now = ch[now][str[i]]; if(End[now]) ans[End[now]]++; int tmp = now; while(last[tmp]) { ans[End[last[tmp]]]++; tmp = last[tmp]; } } } int main() { int n,now,T; scanf("%d",&T); while(T--) { scanf("%d",&n); memset(ch,0,sizeof(ch)); memset(End,0,sizeof(End)); memset(ans,0,sizeof(ans)); memset(last,0,sizeof(last)); memset(sum,0,sizeof(sum)); cur = 1; int len; for(int i=1; i<=n; i++) { scanf("%s",str0[i]); len = strlen(str0[i]); now = 0; for(int j=0; j<len; j++) { str0[i][j]-='a'; if(ch[now][str0[i][j]]==0) ch[now][str0[i][j]] = cur++; now = ch[now][str0[i][j]]; str0[i][j]+='a'; } if(End[now]) sum[End[now]]++; else { sum[i] = 1; End[now] = i; } } get_fail(); scanf("%s",str); Find(); int res=0; for(int i=1; i<=n; i++) { if(ans[i]) res+=sum[i]; //sum+=ans[i]; } printf("%d ",res); } }