模板:
struct Trie{
static const int maxt = 1e7+5;
int rt, id, tot, t[maxt][2];
int cnt[maxt], val[maxt], end[maxt];
inline int newnode(){
++tot;
t[tot][0] = t[tot][1] = 0;
cnt[tot] = end[tot] = val[tot] = 0;
return tot;
}
inline void init(){
tot = 0;
rt = newnode();
}
inline void add(int x){
rt = 1;
for(int i=31; ~i; i--){
id = x >> i & 1;
if(!t[rt][id]) t[rt][id] = newnode();
rt = t[rt][id];
++cnt[rt];
}
end[rt] = 1, val[rt] = x;
}
inline int query(int x){
rt = 1;
for(int i=31; ~i; i--){
id = x >> i & 1;
if(t[rt][id^1]) rt = t[rt][id^1];
else rt = t[rt][id];
}
return x ^ val[rt];
}
} t;
HDU 1251 统计难题
PS:统计前缀出现次数
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2000010;
int tot, tr[maxn][30], sum[maxn];
void insert(char *s, int rt){
for(int i=0; s[i]; i++){
int id = s[i]-'a';
if(tr[rt][id]==0){
tr[rt][id] = ++tot;
}
rt = tr[rt][id];
sum[rt]++;
}
}
int query(char *s, int rt){
for(int i=0; s[i]; i++){
int id = s[i]-'a';
if(tr[rt][id]==0) return 0;
rt = tr[rt][id];
}
return sum[rt];
}
int main(){
char s[15];
tot = 0;
while(gets(s)){
if(s[0]=='\0') break;
insert(s, 0);
}
while(~scanf("%s", s)){
printf("%d\n", query(s, 0));
}
}
POJ 2001 Shortest Prefixes
PS:求最短、没有歧义的前缀
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2000010;
int tot, tr[maxn][30], sum[maxn];
void insert(char *s, int rt) {
for(int i=0; s[i]; i++) {
int id = s[i]-'a';
if(tr[rt][id]==0) {
tr[rt][id] = ++tot;
}
rt = tr[rt][id];
sum[rt]++;
}
}
void query(char *s, int rt) {
string ans = "";
for(int i=0; s[i]; i++) {
int id = s[i]-'a';
ans += s[i];
rt = tr[rt][id];
if(sum[rt]==1) {
cout<<s<<" "<<ans<<endl;
return;
}
}
cout<<s<<" "<<s<<endl;
}
int main() {
char s[1005][25];
tot = 0;
int cnt = 0;
while(~scanf("%s", s[cnt])) {
insert(s[cnt++], 0);
}
for(int i=0; i<cnt; i++) {
query(s[i], 0);
}
}