#include <bits/stdc++.h>
using namespace std;
struct Node
{
Node *ch[26];
unsigned height = 0;
bool z = 0;
};
void trie_insert(Node *x, string const &s, size_t i = 0)
{
if (i == s.size())
x->z = 1;
else
{
if (!x->ch[s[i] - 'a'])
{
x->ch[s[i] - 'a'] = (Node *)calloc(1, sizeof(Node));
memset(x->ch[s[i] - 'a']->ch, 0, sizeof x->ch[s[i] - 'a']->ch);
}
trie_insert(x->ch[s[i] - 'a'], s, i + 1);
x->height = x->ch[s[i] - 'a']->height + 1;
}
}
void trie_destroy(Node *x)
{
for (unsigned i = 0; i < 26; i++)
if (x->ch[i])
{
trie_destroy(x->ch[i]);
free(x->ch[i]);
}
}
void trie_dfs(Node *x, string &traversal)
{
if (x->z)
traversal.push_back('P');
vector<pair<unsigned, unsigned>> children;
for (unsigned i = 0; i < 26; i++)
{
if (x->ch[i])
{
children.emplace_back(x->ch[i]->height, i);
}
}
sort(children.begin(), children.end());
for (auto const &[ignore, i] : children)
{
if (x->ch[i])
{
traversal.push_back(i + 'a');
trie_dfs(x->ch[i], traversal);
traversal.push_back('-');
}
}
}
int main()
{
size_t n;
cin >> n;
Node root;
memset(root.ch, 0, sizeof root.ch);
for (size_t i = 0; i < n; i++)
{
string s;
cin >> s;
trie_insert(&root, s);
}
string traversal;
trie_dfs(&root, traversal);
trie_destroy(&root);
while (traversal.back() == '-')
traversal.pop_back();
cout << traversal.size() << '\n';
for (char const &c : traversal)
cout << c << '\n';
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Correct |
0 ms |
212 KB |
Output is correct |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
1 ms |
212 KB |
Output is correct |
2 |
Incorrect |
0 ms |
212 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
0 ms |
212 KB |
Output is correct |
2 |
Incorrect |
0 ms |
212 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
212 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
464 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
3 ms |
1748 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
13 ms |
5864 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
38 ms |
14688 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
86 ms |
36408 KB |
Output is correct |
2 |
Correct |
175 ms |
83236 KB |
Output is correct |
3 |
Incorrect |
105 ms |
42732 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
71 ms |
28468 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |