字典树

今晚再SOJ上做一道题,写了好久终于把自己想要的结果写出来了,提交WA,发现做的时候把题意理解错了……

 

然后再此贴一下写出的动态创建的字典树……

 

不要浪费……

 

#include <iostream> #include <stdio.h> using namespace std; struct node { char c; node *brother; node *son; }; int cal(node *root) { int sum=0; if (root==NULL) return 1; while(root) { sum += cal(root->son); root = root->brother; } delete root; return sum; } int main() { int n,i,j; char s[1001]; node *head, *temp; head = new node(); while(scanf("%d", &n)!=EOF) { if (n==0) break; head->brother = NULL; head->son = NULL; for (i=0; i<n; i++) { scanf("%s", s); temp = head; for (j=0; s[j]!='/0'; j++) { if (temp->son==NULL) { temp->son = new node(); temp = temp->son; temp->c = s[j]; temp->brother = NULL; temp->son = NULL; } else { temp = temp->son; while(temp->c!=s[j]) { if (temp->brother==NULL) break; else temp = temp->brother; } if (temp->c!=s[j]) { temp->brother = new node(); temp = temp->brother; temp->c = s[j]; temp->brother = NULL; temp->son = NULL; } } } } printf("%d/n", cal(head->son)); } return 0; }

 

下周日省赛,继续准备打酱油……路漫漫啊……

你可能感兴趣的:(字典树)