poj 2001 Shortest Prefixes(字典树)

来源:互联网 发布:童年阴影知乎 编辑:程序博客网 时间:2024/04/18 19:28
#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>using namespace std;const int N = 1010;const int kind = 26;char str[N][25];struct node {    int num;    node* next[kind];    node() {        num = 1;        memset(next, 0, sizeof(next));    }};void Insert(node* root, char *s) {    node* p = root;    int i, index;    int len = strlen(s);    for(i = 0; i < len; i++) {        index = s[i] - 'a';        if(p->next[index] == NULL) {            p->next[index] = new node();        }        else {            p->next[index]->num++;        }        p = p->next[index];    }}void Find(node* root, int ca) {    int i = 0, index = 0;    for(i = 0; i <= ca; i++) {        node* p = root;        int len = strlen(str[i]);        char *s = str[i];        cout << s << ' ';        for(int j = 0; j < len; j++) {            cout << s[j];            index = s[j] - 'a';            if(p->next[index]->num == 1) {                break;            }            p = p->next[index];        }        cout << endl;    }}int main() {    node* root = new node();    int i = 0, ca = 0;    while(scanf("%s", str[i]) == 1) {        Insert(root, str[i]);        i++;    }    ca = i - 1;    Find(root, ca);    return 0;}

原创粉丝点击