This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int ALPHABET_SIZE = 26;
class TrieNode {
public:
TrieNode* children[ALPHABET_SIZE];
bool isLeaf;
TrieNode() {
for (int i = 0; i < ALPHABET_SIZE; i++) {
children[i] = nullptr;
}
isLeaf = false;
}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string &word) {
TrieNode* cur = root;
for (char &c : word) {
if (cur->children[c - 'a'] == nullptr)
cur->children[c - 'a'] = new TrieNode();
cur = cur->children[c - 'a'];
}
cur->isLeaf = true;
}
void traverse(string &longest, vector<char> &ans) {
dfs(root, longest, ans, 0);
}
void dfs(TrieNode* node, string &longest, vector<char> &ans, int pos) {
if (node == nullptr)
return;
if (node->isLeaf)
ans.push_back('P');
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (node->children[i] != nullptr && (pos == -1 || i + 'a' != longest[pos])) {
ans.push_back('a' + i);
dfs(node->children[i], longest, ans, -1);
ans.push_back('-');
}
}
if (pos != -1 && node->children[longest[pos] - 'a']) {
ans.push_back(longest[pos]);
dfs(node->children[longest[pos] - 'a'], longest,
ans, pos + 1);
}
}
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
vector<string> a(n);
string longest = "";
Trie* trie = new Trie();
for (int i = 0; i < n; ++i) {
cin >> a[i];
if (a[i].length() > longest.length())
longest = a[i];
trie->insert(a[i]);
}
vector<char> ans;
trie->traverse(longest, ans);
cout << ans.size() << "\n";
for (auto &c : ans) {
cout << c << "\n";
}
return 0;
}
# | 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... |