https://www.acmicpc.net/problem/5670
5670번: 휴대폰 자판
휴대폰에서 길이가 P인 영단어를 입력하려면 버튼을 P번 눌러야 한다. 그러나 시스템프로그래밍 연구실에 근무하는 승혁연구원은 사전을 사용해 이 입력을 더 빨리 할 수 있는 자판 모듈을 개발
www.acmicpc.net
트라이 구현하고
문제 조건 따라
디버깅 해가면서 풀면 된다.
각 테스트 케이스마다 한 줄에 걸쳐 문제의 정답을 소수점 둘째 자리까지 반올림하여 출력한다.
fixed << setprecision(2) << result;
#include <iomanip>
double result = (double)sum / words.size();
cout << fixed << setprecision(2) << result << '\n'; // 출력 정밀도 2 자리로 설정
<소스 코드>
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
|
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
struct Node {
Node* next[26];
bool isEnd;
int how_many;
Node()
{
isEnd = false;
fill(next, next + 26, nullptr);
how_many = 0;
}
~Node()
{
for (int i = 0; i < 26; i++)
if (next[i])
delete next[i];
}
void add(const string &str, int genzai)
{
if (genzai >= str.length())
{
isEnd = true;
return;
}
else
{
int idx = str[genzai] - 'a';
if (next[idx] == NULL)
{
how_many++;
next[idx] = new Node();
}
next[idx]->add(str, genzai + 1);
}
}
int count(const string &str, int genzai, int cnt)
{
if (genzai == str.length())
return cnt;
int ans = 0;
int word_index = str[genzai] - 'a';
// 1. 첫 번째 문자는 무시하고 들어간다. -> 나중에 + 1 해줌
// 2. how_many가 1보다 크다 OR how_many가 1인데 isEnd가 true
// 3. 마지막 문자가 아니다.
if (genzai != 0 && ((isEnd && how_many == 1) || how_many > 1) && next[word_index] != NULL)
ans = next[word_index]->count(str, genzai + 1, cnt + 1);
else
ans = next[word_index]->count(str, genzai + 1, cnt);
return ans;
}
};
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int n;
while (cin >> n)
{
Node root;
vector<string> words(n);
for (int i = 0; i < n; ++i)
cin >> words[i];
for (int i = 0; i < n; i++)
{
root.add(words[i], 0);
}
int sum = 0;
for (int i = 0; i < n; i++)
{
// 첫 번째 문자 cnt + 1
sum += root.count(words[i], 0, 0) + 1;
}
double result = (double)sum / words.size();
cout << fixed << setprecision(2) << result << '\n'; // 출력 정밀도 2 자리로 설정
}
}
|
cs |