Submission #448041

#TimeUsernameProblemLanguageResultExecution timeMemory
448041Alex_tz307Type Printer (IOI08_printer)C++17
100 / 100
163 ms99520 KiB
#include <bits/stdc++.h>

using namespace std;

struct node {
  int level;
  bool is_end, is_marked;
  node *son[26];

  node() {
    level = is_end = is_marked = 0;
    for (int i = 0; i < 26; ++i)
      son[i] = nullptr;
  }
};

string s;
int longest;
bool found;
vector<char> sol;

void max_self(int &x, int y) {
  x = max(x, y);
}

void Insert(node *nod, int p) {
  max_self(longest, nod->level);
  if (p == (int)s.size()) {
    nod->is_end = true;
    return;
  }
  int nxt = s[p] - 'a';
  if (nod->son[nxt] == nullptr) {
    nod->son[nxt] = new node;
    nod->son[nxt]->level = nod->level + 1;
  }
  Insert(nod->son[nxt], p + 1);
}

bool mark(node *nod) {
  bool is_leaf = true;
  for (int i = 0; i < 26 && is_leaf; ++i)
    if (nod->son[i] != nullptr)
      is_leaf = false;
  if (is_leaf) {
    if (found)
      return false;
    if (nod->level == longest) {
      nod->is_marked = true;
      found = true;
      return true;
    }
    return false;
  }
  bool ok = false;
  for (int i = 0; i < 26 && !ok; ++i)
    if (nod->son[i] != nullptr)
      ok |= mark(nod->son[i]);
  nod->is_marked = ok;
  return ok;
}

void solve(node *nod) {
  if (nod->is_end)
    sol.emplace_back('P');
  int marked = -1;
  for (int i = 0; i < 26; ++i) {
    if (nod->son[i] != nullptr) {
      if (nod->son[i]->is_marked == false) {
        sol.emplace_back('a' + i);
        solve(nod->son[i]);
        sol.emplace_back('-');
      } else marked = i;
    }
  }
  if (marked == -1)
    return;
  sol.emplace_back('a' + marked);
  solve(nod->son[marked]);
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int n;
  cin >> n;
  node* root = new node;
  for (int i = 0; i < n; ++i) {
    cin >> s;
    Insert(root, 0);
  }
  mark(root);
  solve(root);
  cout << sol.size() << '\n';
  for (auto it : sol)
    cout << it << '\n';
  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...