#include <bits/stdc++.h>
using namespace std;
// Trie
vector<vector<int>> nex(500001, vector<int>(26));
vector<int> endpoint(500001); // marks if a word is done
vector<int> depth(500001, -1);
int num_nodes = 0;
void trie_insert(string s) {
int cur = 0;
for (char c : s) {
if (!nex[cur][c-'a'])
nex[cur][c-'a'] = ++num_nodes;
cur = nex[cur][c-'a'];
}
endpoint[cur]=1;
}
// Find max depth of all nodes in subtree
int depth_dfs(int cur) {
if (endpoint[cur]) {
depth[cur]=1;
return 1;
}
int deepest = 0;
for (int i=0;i<26;i++) {
if (!nex[cur][i]) continue;
deepest = max(deepest, depth_dfs(nex[cur][i]));
}
depth[cur] = deepest+1;
return deepest+1;
}
int main() {
int N; cin>>N;
vector<string> S(N);
for (int i=0;i<N;i++)
cin >> S[i];
for (string s : S)
trie_insert(s);
// Calculate depths of every node
depth_dfs(0);
// Perform backtracking dfs, while prioritizing shorter depths
// (this ensures we end on the longest word, which minimizes moves)
vector<char> ans;
auto dfs = [&](auto &&self, int cur) -> void {
// end of word (but dont terminate early, e.g. "cat,cats")
if (endpoint[cur]) {
ans.push_back('P');
}
// Visit child nodes in order of their depths
vector<array<int,3>> candidates;
for (int i=0;i<26;i++) {
if (!nex[cur][i]) continue;
int nxt = nex[cur][i];
candidates.push_back({depth[nxt], nxt, i});
}
sort(candidates.begin(),candidates.end());
for (auto [_,nxt,chr] : candidates) {
ans.push_back((char)(chr+'a'));
self(self, nxt);
ans.push_back('-');
}
};
dfs(dfs, 0);
// Get rid of final '-'s (we don't need to clean up)
while (ans.back() == '-')
ans.pop_back();
// Print results
cout << ans.size() << '\n';
for (char c : ans)
cout << c << '\n';
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
38 ms |
70748 KB |
Output is correct |
2 |
Correct |
39 ms |
70748 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
36 ms |
70740 KB |
Output is correct |
2 |
Correct |
37 ms |
70824 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
36 ms |
70748 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
38 ms |
70748 KB |
Output is correct |
2 |
Correct |
37 ms |
70664 KB |
Output is correct |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
39 ms |
70732 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
42 ms |
70748 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
43 ms |
71088 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
55 ms |
71592 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
71 ms |
72904 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
66 ms |
72648 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |