题意:问许多单词中,前缀是某个字符串的个数有多少个;
思路: 用字典树建立,每个节点带上num,记录每次insert是,经过这个点的次数,
每次询问,找到这个前缀对应的节点的num就ok
这道题,c++过,g++不行
ac代码:
#include <iostream> #include <cstring> #include <algorithm> #include <string> #include <cstdio> using namespace std; const int maxn = 500000; struct node { node * s[26]; int num; }; node a[maxn],*rt; int p = 0; char str[11]; node * newNode() { memset(a[p].s,0,sizeof(a[p].s)); a[p].num = 0; return &a[p++]; } void insert(char * str) { node * cur = rt; cur->num++; while( *str != ‘\0‘) { int t = *(str++) - ‘a‘; if(cur->s[t]==0) cur-> s[t]=newNode(); cur = cur->s[t]; cur -> num++; } } int getans(char *str) { node *cur = rt; while(*str!=‘\0‘) { int t = *(str++) - ‘a‘; if(cur->s[t]==0)return 0; cur = cur -> s[t]; } return cur->num; } int main(){ rt = newNode(); gets(str); while(str[0]!=‘\0‘) { insert(str); gets(str); } while(~scanf("%s",str)) { printf("%d\n",getans(str)); } return 0; }
原文地址:https://www.cnblogs.com/ckxkexing/p/8996714.html
时间: 2024-10-10 21:37:00