标签:struct pre insert color input next == rgb return
banana band bee absolute acm ba b band abc
2 3 1 0
#include <stdio.h> #include <string.h> #include <stdlib.h> struct Node{ struct Node *nextAlph[26]; int num; } root; void insert(char *str) { Node *p = &root; int id; while(*str){ id = *str - ‘a‘; if(p->nextAlph[id] == NULL){ p->nextAlph[id] = (Node *)malloc(sizeof(Node)); p = p->nextAlph[id]; memset(p->nextAlph, 0, sizeof(p->nextAlph)); p->num = 0; }else p = p->nextAlph[id]; ++p->num; ++str; } } int FIND(char *str) { Node *p = &root; int id; while(*str){ id = *str - ‘a‘; if(p->nextAlph[id] == NULL) return 0; p = p->nextAlph[id]; ++str; } return p->num; } int main() { //freopen("stdin.txt", "r", stdin); char str[12]; while(gets(str), *str) insert(str); while(gets(str) != NULL) printf("%d\n", FIND(str)); return 0; }
#include <stdio.h> #include <string.h> bool alpha[12][26]; int num[12][26]; void insert(char *str) { int id, i; for(i = 0; str[i]; ++i){ id = str[i] - ‘a‘; alpha[i][id] = true; ++num[i][id]; } } int getNum(char *str) { int id, i; for(i = 0; str[i]; ++i){ id = str[i] - ‘a‘; if(alpha[i][id] == false) return 0; } return num[i - 1][id]; } int main() { //freopen("stdin.txt", "r", stdin); char str[12]; while(gets(str), *str) insert(str); while(gets(str)) printf("%d\n", getNum(str)); return 0; }
2014.12.16更新
#include <stdio.h> #include <string.h> #define maxNode 1000000 char str[12]; struct Trie { int ch[maxNode][26]; int val[maxNode], sz; Trie() { memset(ch[0], 0, sizeof(ch[0])); sz = 1; } int idx(char ch) { return ch - ‘a‘; } void insert(char *str) { int u = 0, id, i, len = strlen(str); for (i = 0; i < len; ++i) { id = idx(str[i]); if (!ch[u][id]) { memset(ch[sz], 0, sizeof(ch[sz])); val[sz] = 0; ch[u][id] = sz++; } u = ch[u][id]; ++val[u]; } } int find(char *str) { int u = 0, id, i, len = strlen(str); for (i = 0; i < len; ++i) { id = idx(str[i]); if (ch[u][id]) u = ch[u][id]; else break; } return i == len ? val[u] : 0; } } T; int main() { // freopen("stdin.txt", "r", stdin); while(gets(str), *str) T.insert(str); while(gets(str)) printf("%d\n", T.find(str)); return 0; }
标签:struct pre insert color input next == rgb return
原文地址:http://www.cnblogs.com/blfbuaa/p/6820675.html