// UUID: 51653dac-a58e-4475-9183-3b03958cec81
#include <bits/stdc++.h>
using namespace std;
#define int long long
vector<char> ans;
int word_count = 0;
int n;
class TrieNode {
public:
TrieNode* children[26];
bool is_leaf;
char c;
bool visited;
bool longest;
TrieNode(char _c) {
longest = false;
visited = false;
c = _c;
is_leaf = false;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
void insert(TrieNode* root, const string& key, bool longest) {
TrieNode* curr = root;
for (char c : key) {
if (curr->children[c - 'a'] == nullptr) {
TrieNode* newNode = new TrieNode(c);
curr->children[c - 'a'] = newNode;
}
curr->longest = longest;
curr = curr->children[c - 'a'];
}
curr->is_leaf = true;
}
void dfs(TrieNode* curr_node)
{
if(curr_node->is_leaf)
{
ans.push_back('P');
word_count++;
}
if(word_count == n) return;
curr_node->visited = true;
TrieNode* longest_node = nullptr;
for(auto node: curr_node->children)
{
if(node != nullptr)
{
if(node->longest)
{
longest_node = node;
continue;
}
if(!node->visited)
{
ans.push_back(node->c);
dfs(node);
if(word_count == n) return;
}
}
}
if(longest_node != nullptr && !longest_node->visited)
{
ans.push_back(longest_node->c);
dfs(longest_node);
if(word_count == n) return;
}
if(curr_node->c != ';') ans.push_back('-');
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
vector<pair<int, string>> v(n);
TrieNode *root = new TrieNode(';');
for(int i = 0; i < n; i++)
{
cin >> v[i].second;
v[i].first = v[i].second.size();
}
sort(v.begin(), v.end());
for(int i = 0; i < n-1; i++) insert(root, v[i].second, false);
insert(root, v[n-1].second, true);
dfs(root);
cout << ans.size();
for(char c: ans) cout << "\n" << c;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |