// SPDX-License-Identifier: CC0-1.0
// Probe the unmodified LevelDB 1.23 block builder and reader, not database I/O.
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "leveldb/comparator.h"
#include "leveldb/iterator.h"
#include "leveldb/options.h"
#include "table/block.h"
#include "table/block_builder.h"
#include "table/format.h"

std::string unhex(const std::string& text) {
  if (text == "-") return "";
  if (text.size() % 2) throw std::runtime_error("Odd hex input");
  std::string out;
  for (size_t i = 0; i < text.size(); i += 2) {
    if (text.find_first_not_of("0123456789abcdef", i) < i + 2)
      throw std::runtime_error("Invalid hex input");
    out.push_back(static_cast<char>(std::stoul(text.substr(i, 2), nullptr, 16)));
  }
  return out;
}
int main() {
  try {
    int interval;
    size_t count;
    while (std::cin >> interval >> count) {
      if (interval < 1 || count > 10000) throw std::runtime_error("Invalid case");
      leveldb::Options options;
      options.block_restart_interval = interval;
      leveldb::BlockBuilder builder(&options);
      std::vector<std::string> keys;
      for (size_t i = 0; i < count; ++i) {
        std::string hex;
        if (!(std::cin >> hex)) throw std::runtime_error("Truncated input");
        auto key = unhex(hex);
        if (i && options.comparator->Compare(keys.back(), key) >= 0)
          throw std::runtime_error("Unsorted input");
        builder.Add(key, "");
        keys.push_back(key);
      }
      std::string encoded = builder.Finish().ToString();
      leveldb::BlockContents contents;
      contents.data = encoded;
      contents.cachable = false;
      contents.heap_allocated = false;
      leveldb::Block block(contents);
      std::unique_ptr<leveldb::Iterator> iter(block.NewIterator(options.comparator));
      iter->SeekToFirst();
      for (const auto& key : keys) {
        if (!iter->Valid() || iter->key().ToString() != key || !iter->value().empty())
          throw std::runtime_error("Native reconstruction mismatch");
        iter->Next();
      }
      if (iter->Valid() || !iter->status().ok()) throw std::runtime_error("Native scan failed");
      for (const auto& key : keys) {
        iter->Seek(key);
        if (!iter->Valid() || iter->key().ToString() != key || !iter->status().ok())
          throw std::runtime_error("Native seek failed");
      }
      const char* digits = "0123456789abcdef";
      std::cout << encoded.size() << " ";
      for (unsigned char byte : encoded) std::cout << digits[byte >> 4] << digits[byte & 15];
      std::cout << "\n";
    }
    if (!std::cin.eof()) throw std::runtime_error("Invalid input");
  } catch (const std::exception& error) {
    std::cerr << error.what() << "\n";
    return 1;
  }
}
