티스토리 뷰

문제 링크입니다 : https://www.acmicpc.net/problem/14425

 

14425번: 문자열 집합

첫째 줄에 문자열의 개수 N과 M (1 ≤ N ≤ 10,000, 1 ≤ M ≤ 10,000)이 주어진다.  다음 N개의 줄에는 집합 S에 포함되어 있는 문자열들이 주어진다. 다음 M개의 줄에는 검사해야 하는 문자열들이 주어�

www.acmicpc.net

 

트라이로 한번 풀어보았다.

 

 

 

#include <iostream>
#include <vector>

using namespace std;

struct Node {
    bool data = false;
    vector<Node*> next;

    Node() {
        data = false;
        next.assign(26, nullptr);
    }
};

void makeNode(Node* cur, const string& str, int index) {
    if(index == str.size()) {
        cur->data = true;
        return;
    }
    if(cur->next[str[index] - 'a'] == nullptr) {
        cur->next[str[index] - 'a'] = new Node();
    }
    makeNode(cur->next[str[index] - 'a'], str, index + 1);
}

bool findNode(Node* cur, const string& str, int index) {
    if(index == str.size()) {
        if(cur->data) return true;
        return false;
    }

    if(cur->next[str[index] - 'a'] == nullptr) return false;
    return findNode(cur->next[str[index] - 'a'], str, index + 1);
}

int main() {
    ios_base :: sync_with_stdio(false); 
    cin.tie(NULL); cout.tie(NULL);

    int N, M;
    cin >> N >> M;

    Node* head = new Node();

    string str;
    for(int i = 0; i < N; i++) {
        cin >> str;
        makeNode(head, str, 0);
    }

    int cnt = 0;
    for(int i = 0; i < M; i++) {
        cin >> str;
        if(findNode(head, str, 0)) cnt++;
    }

    cout << cnt;

    return 0;
}

 

 

 

개발 환경 : vscode

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

 

'알고리즘 > 백준(BOJ)' 카테고리의 다른 글

백준 - 3584 가장 가까운 공통 조상  (0) 2020.07.21
백준 - 1005 ACM Craft  (0) 2020.07.19
백준 - 14725 개미굴  (0) 2020.07.19
백준 - 10266 시계 사진들  (0) 2020.07.19
백준 - 1305 광고  (0) 2020.07.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/07   »
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
글 보관함