字符串训练之四
https://www.luogu.org/problem/P2264
看一眼就是水题
方法应该很多,都可以乱搞出来
我就找了两个比较好的做法
一个是trie,还有一个是set
trie
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<iostream>
#include<algorithm>
#include<string>
#define rep(i,x,y) for(register int i = x;i <= y;++i)
#define repd(i,x,y) for(register int i = x;i >= y;--i)
using namespace std;
typedef long long ll;
int n,sz,ans,cnt = 1,val[1000000];
char trie[100000][27];
void trie_build(char*s,int len)
{
int x = 0;
rep(i,1,len) {
if(!trie[x][s[i]]) trie[x][s[i]] = ++sz;
x = trie[x][s[i]];
}
val[x] = -1;
}
bool trie_find(char*s,int len)
{
int x = 0;
rep(i,1,len)
{
if(s[i] < 'a' || s[i] > 'z' || !trie[x][s[i]]) return false;
x = trie[x][s[i]];
}
if(val[x] != cnt && val[x])return val[x] = cnt,true;
return false;
}
int main()
{
freopen("qs.in","r",stdin);
scanf("%d",&n);getchar();
char s[100],c;
int len;
rep(i,1,n) {
len = 0;
while((c = getchar()) != '\n' && c != ' ') {
if(c >= 'A' && c <= 'Z') c += 32;
s[++len] = c;
}
trie_build(s,len);
}
len = 0;
while((c = getchar()) != EOF)
{
if(c == ' ' || c == '.' || c == ',') {
if(trie_find(s,len)) ans++;
len = 0; if(c == '.') ++cnt;
continue;
}
if(c >= 'A' && c <= 'Z') c += 32;
s[++len] = c;
}
if(trie_find(s,len)) ans++;
cout<<ans;
return 0;
}
set
#include<bits/stdc++.h>
using namespace std;
set<string>se,se2;
int ans,n;
int main()
{
scanf("%d",&n);
string a;
for(int i=1;i<=n;i++){
cin>>a;
for(int i=0;i<a.length();i++)
if(a[i]>='a'&&a[i]<='z') a[i]-=32;
se.insert(a);
}
char ch=getchar();
string b;
while(scanf("%c",&ch)==1){
if(ch=='\n')break;
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')){
if(ch>='a'&&ch<='z')ch=ch-32;
b+=ch;
}
else{
if(!b.empty()){
if(se.count(b))se2.insert(b);
b.clear();
}
if(ch=='.')ans+=se2.size(),se2.clear();
}
}
printf("%d\n",ans);
return 0;
}