Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct Elem {
- struct Elem *parent;
- int amount, len, all;
- struct Elem *sons[26];
- };
- struct Elem *InitTrie()
- {
- struct Elem *t = (struct Elem *)malloc(sizeof(struct Elem));
- t->amount = 0;
- t->parent = NULL;
- for (int i = 0; i < 26; i++) t->sons[i] = NULL;
- t->len = 0;
- t->all = 0;
- return t;
- }
- struct Elem *Descend(struct Elem *t, char *k, int len)
- {
- struct Elem *x = t, *y;
- for (int i = 0; i < len; i++) {
- y = x->sons[(int)k[i] - 97];
- if (y == NULL) return x;
- x = y;
- }
- return x;
- }
- void Insert(struct Elem *t, char *k, int len)
- {
- struct Elem *x = Descend(t, k, len);
- int i = x->len, l, j;
- if (i == len) {
- if (x->amount != 1) {
- x->amount = 1;
- struct Elem *y;
- while (1) {
- y = x->parent;
- if (y == NULL) break;
- y->all++;
- x = y;
- }
- }
- }
- else {
- struct Elem *now = x;
- for (j = i + 1; j <= len; j++) {
- struct Elem *y = (struct Elem *)malloc(sizeof(struct Elem));
- y->len = j;
- if (j == len) y->amount = 1;
- else y->amount = 0;
- for (l = 0; l < 26; l++) y->sons[l] = NULL;
- y->all = 0;
- y->parent = x;
- x->sons[(int)k[j - 1] - 97] = y;
- x->all++;
- x = y;
- }
- while (1) {
- x = now->parent;
- if (x == NULL) break;
- x->all++;
- now = x;
- }
- }
- }
- void Delete(struct Elem *t, char *k, int len)
- {
- struct Elem *y, *x = Descend(t, k, len);
- x->amount = 0;
- while (1) {
- y = x->parent;
- if (y == NULL) break;
- y->all--;
- x = y;
- }
- }
- void SuperFree(struct Elem *t)
- {
- if (t != NULL) {
- for (int i = 0; i < 26; i++) SuperFree(t->sons[i]);
- free(t);
- }
- }
- int main()
- {
- int n, i, len;
- char cur[8];
- char now[100000];
- scanf("%d\n", &n);
- struct Elem *t = InitTrie();
- for (i = 0; i < n; i++) {
- scanf("%s ", cur);
- if (0 == strcmp(cur, "INSERT")) {
- scanf("%s", now);
- len = (int)strlen(now);
- Insert(t, now, len);
- }
- if (0 == strcmp(cur, "PREFIX")) {
- scanf("%s", now);
- len = (int)strlen(now);
- struct Elem *x = Descend(t, now, len);
- if (x->len < len) printf("0\n");
- else printf("%d %d\n", x->amount, x->amount + x->all);
- }
- if (0 == strcmp(cur, "DELETE")) {
- scanf("%s", now);
- len = (int)strlen(now);
- Delete(t, now, len);
- }
- if (i != n - 1) scanf("\n");
- }
- SuperFree(t);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement