Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define size 26
- struct elem {
- char ** v;
- struct elem ** array;
- struct elem * parent;
- int count;
- };
- struct elem * Init(struct elem * parent) {
- struct elem * a = (struct elem *)malloc(sizeof(struct elem));
- a->v = NULL;
- a->parent = parent;
- a->count = 0;
- a->array = (struct elem**)malloc(size*sizeof(struct elem*));
- for(int i = 0;i < size;i++) {
- a->array[i] = NULL;
- }
- return a;
- }
- void Insert(struct elem * root,char * v) {
- struct elem * a = root;
- int length = strlen(v), i =0;
- while(i < length) {
- a->count++;
- struct elem * b = a->array[v[i] - 'a'];
- if (b == NULL) {
- break;
- }
- a = b;
- i++;
- }
- if ((a->v != NULL) && (i == length)) {
- a->v = &v;
- i--;
- while(i > 0) {
- a->count--;
- struct elem * b = a->parent;
- if (b == NULL) {
- break;
- }
- a = b;
- i--;
- }
- }
- else {
- if (i == length) {
- a->count++;
- }
- for(int j = i;j < length;j++) {
- a->array[v[j]-'a'] = Init(a);
- a = a->array[v[j]-'a'];
- a->count++;
- }
- a->v = &v;
- }
- }
- int Prefix(struct elem * root,char * v) {
- struct elem * a = root;
- int length = strlen(v),sum = 0,i = 0;
- while(i < length) {
- struct elem * b = a->array[v[i] - 'a'];
- if (b == NULL) {
- break;
- }
- a = b;
- i++;
- }
- if (i != length) {
- return 0;
- }
- else {
- return a->count;
- }
- }
- void Delete(struct elem * root,char * v) {
- struct elem * a = root;
- int i = 0,length = strlen(v);
- while(i < length) {
- a->count--;
- struct elem * b = a->array[v[i] - 'a'];
- if (b == NULL) {
- break;
- }
- a = b;
- i++;
- }
- a->count--;
- a->v = NULL;
- }
- void freebor(struct elem * elem) {
- if (elem == NULL) ;
- else {
- for(int i = 0;i < size;i++) {
- if (elem->array[i] != NULL) {
- freebor(elem->array[i]);
- }
- }
- free(elem->array);
- free(elem);
- }
- }
- int main()
- {
- char name[10];
- char v[100000];
- int n;
- scanf("%d" , &n);
- struct elem * root = (struct elem *)malloc(sizeof(struct elem));
- root->parent = NULL;
- root->count = 0;
- root->v = NULL;
- root->array = (struct elem**)malloc(size*sizeof(struct elem*));
- for(int i = 0;i < size;i++) {
- root->array[i] = NULL;
- }
- for(int i = 0;i < n;i++) {
- scanf("%s%s" , name , v);
- if ((strcmp(name,"INSERT")) == 0) Insert(root,v);
- else {
- if ((strcmp(name,"DELETE")) == 0) Delete(root,v);
- else printf("%d\n" , Prefix(root,v));
- }
- }
- freebor(root);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement