본문 바로가기

소프트웨어/Algorithm

[Algo] Trie 간단 insert, find code

TRIE를 이용하여 insert 및 find, print를 하는 코드이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <iostream>
using namespace std;
 
#define rr register int
#define null 0
 
typedef struct trie {
    bool finish;
    trie* child[26];
    trie() {
        finish = 0;
        for (rr i =0; i < 26; i++)
            child[i] = null;
    }
    void insert(char* str) {
        if (*str == null) {
            finish = true;
            return;
        }
 
        int id = *str - 'a';
        if(child[id] == null)
            child[id] = new trie();
        child[id]->insert(str + 1);
    }
    bool find(char* str) {
        if (*str == null) {
            return finish;
        }
        int id = *str - 'a';
        if (child[id] == null)
            return false;
        return child[id]->find(str + 1);
    }
    void printAll(int id) {
        //cout << ('a' + id) << endl;
        printf("%c", ('a' + id));
        if (finish)
            cout << endl;
        for (rr i = 0; i < 26; i++) {
            if(child[i] != null)
                child[i]->printAll(i);
        }
    }
};
 
trie root;
 
void printAll(trie* node, char buffer[10], int id) {
    if (node->finish) {
        buffer[id] = null;
        cout << buffer << endl;
    }
    for (rr i = 0; i < 26; i++) {
        if (node->child[i] != null) {
            buffer[id] = 'a' + i;
            printAll(node->child[i], buffer, id + 1);
        }
    }
}
 
int main(void) {
 
    cout << "d"<<endl;
    {
        char input[] = "string";
        root.insert(input);
    } {
        char input[] = "strong";
        root.insert(input);
    }
    int a = 0;
    {
        char input[] = "string";
        cout << root.find(input) << endl;
    }
    {
        char input[] = "strin";
        cout << root.find(input) << endl;
    }
    {
        char input[] = "strongg";
        cout << root.find(input) << endl;
    }
    {
        char input[] = "strong";
        cout << root.find(input) << endl;
    }
 
    cout << "all node 탐색" << endl;
    for(rr i =0; i <26; i++)
        if(root.child[i] != null)
            root.printAll(i); //
 
    cout << "all node 정렬" << endl;
    for (rr i = 0; i < 26; i++) {
        if (root.child[i] != null) {
            char buffer[10= { 0, };
            printAll(&root, buffer, 0);
        }
    }
 
    return 0;
}
cs

'소프트웨어 > Algorithm' 카테고리의 다른 글

[Algorithm] 0-1 Knapsack Problem  (0) 2021.04.02
Math] Spline Interpolation  (0) 2019.01.02
Dijkstra  (0) 2015.09.20
gtk study 예정사항들  (0) 2015.09.20
week3] dijkstra(heap sort, priority queue)  (0) 2015.09.20
week2] sort, tree, heap, graph 자료구조 마무리  (0) 2015.09.20
Heap Sort  (0) 2015.09.14