AcWing 835. Trie字符串统计
原题链接
简单
作者:
Value
,
2020-05-11 21:58:32
,
所有人可见
,
阅读 485
unordered_map or map
#include <iostream>
#include <cstring>
#include <map>
#include <unordered_map>
using namespace std;
// map<string, int> mp;
unordered_map<string, int> mp;
int main(){
int n;
cin >> n;
char op;
string s;
while(n -- ){
cin >> op >> s;
if(op == 'Q'){
cout << mp[s] << endl;
}else mp[s] += 1;
}
return 0;
}
Trie
#include <iostream>
using namespace std;
const int N = 100010;
int str[N][30], cnt[2*10010], id;
int insert(char s[]){
int p = 0;
for(int i = 0; s[i]; i ++ ){
int u = s[i] - 'a';
if(!str[p][u]) str[p][u] = ++ id;
p = str[p][u];
}
cnt[p] ++ ;
}
int query(char s[]){
int p = 0;
for(int i = 0; s[i]; i ++ ){
int u = s[i] - 'a';
if(!str[p][u]) return 0;
p = str[p][u];
}
return cnt[p];
}
int main(){
int n;
cin >> n;
char op;
char s[N];
while(n -- ){
cin >> op >> s;
if(op == 'Q') cout << query(s) << endl;
else insert(s);
}
return 0;
}