알고리즘/BOJ 문제풀이

[백준] 5670 휴대폰 자판

4Legs 2021. 3. 2. 23:15

문제 링크 : www.acmicpc.net/problem/5670

 

5670번: 휴대폰 자판

휴대폰에서 길이가 P인 영단어를 입력하려면 버튼을 P번 눌러야 한다. 그러나 시스템프로그래밍 연구실에 근무하는 승혁연구원은 사전을 사용해 이 입력을 더 빨리 할 수 있는 자판 모듈을 개발

www.acmicpc.net

문제 유형

자료 구조, 트라이

 

트라이 자료구조로 해결이 가능한 문제이다.

트라이의 find 함수에서, 다음과 같은 경우에 반환값을 1 증가시켜 정답을 구하면 된다.

  • 다른 문자열의 끝을 지나는 경우 (코드의 finish)
  • 자식의 수가 2 이상인 트라이 객체를 지날 경우
  • root 트라이 객체일 경우 (최초 1번의 입력)

 

[코드]

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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
 
using namespace std;
typedef pair<intint> p;
 
int n, answer;
vector<string> dict;
 
class Trie {
private:
    Trie* childs[26];
    int child_cnt;
    bool isRoot, finish;
 
public:
    Trie(bool isroot) {
        for (int i = 0; i < 26; i++) childs[i] = NULL
        finish = false;
        isRoot = isroot;
        child_cnt = 0;
    }
 
    ~Trie() {
        for (int i = 0; i < 26; i++)
            if (childs[i] != NULLdelete childs[i];
    }
 
    void insert(const char* cur) {
        if (*cur == '\0') {
            finish = true;
            return;
        }
        int pos = *cur - 'a';
 
        if (childs[pos] == NULL) {
            childs[pos] = new Trie(false);
            child_cnt++;
        }
 
        childs[pos]->insert(cur + 1);
    }
 
    void find(const char* cur) {
        if (*cur == '\0'return;
        int pos = *cur - 'a';
 
        if (isRoot) answer++;
        else {
            if (child_cnt > 1) answer++;
            else if (finish) answer++;
        }
 
        childs[pos]->find(cur + 1);
    }
};
 
void init() {
    string input;
 
    dict.clear();
    for (int i = 0; i < n; i++) {
        cin >> input;
        dict.push_back(input);
    }
}
 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(NULL);
 
    while (cin >> n) {
        init();
        Trie root = Trie(true);
        for (int i = 0; i < dict.size(); i++) root.insert(dict[i].c_str());
 
        int total = 0;
        for (int i = 0; i < dict.size(); i++) {
            //cout << dict[i] << " : ";
            //printf("%d\n", root.find(dict[i].c_str(), 0));
            answer = 0;
            root.find(dict[i].c_str());
            total += answer;
        }
 
        double res = (double)total / n;
        printf("%.2lf\n", res);
    }
 
    return 0;
}
cs

 

'알고리즘 > BOJ 문제풀이' 카테고리의 다른 글

[백준] 19237 어른 상어  (0) 2021.03.30
[백준] 17822 원판 돌리기  (0) 2021.03.30
[백준] 8452 그래프와 쿼리  (0) 2021.03.02
[백준] 11003 최솟값 찾기  (0) 2021.02.28
[백준] 1945 직사각형  (0) 2021.02.27