File size: 2,101 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "io.hpp"
#include <fstream>
#include <stdexcept>
using namespace std;

// I/O adapter for Navarro's unmodified integer Re-Pair compressor.
// Rank-sorted query strings make every dictionary concatenation an ordered union.
static void put(ofstream& f, int x) { f.write(reinterpret_cast<char*>(&x), sizeof x); }
static bool get(ifstream& f, int& x) {
    return bool(f.read(reinterpret_cast<char*>(&x), sizeof x));
}
int main(int argc, char** argv) {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    if (argc != 3) return 2;
    Input in;
    string mode = argv[1], base = argv[2];
    if (mode == "encode") {
        ofstream seq(base, ios::binary);
        for (int q = 0; q < in.m; ++q) {
            auto [l,r] = in.spans[q];
            for (int rank = 1; rank <= in.n; ++rank)
                if (l <= in.pos[rank] && in.pos[rank] <= r) put(seq, rank - 1);
            // Each delimiter occurs once: Re-Pair cannot select a pair containing it.
            put(seq, in.n + q);
        }
        return seq ? 0 : 3;
    }
    if (mode != "decode") return 2;
    ifstream rules(base + ".R", ios::binary), seq(base + ".C", ios::binary);
    int alph;
    if (!get(rules, alph) || alph != in.n + in.m) return 3;
    vector<int> ids(alph, 0);
    for (int rank = 1; rank <= in.n; ++rank) ids[rank-1] = in.pos[rank];
    Output out(in.n);
    int a,b;
    while (get(rules,a)) {
        if (!get(rules,b) || a < 0 || b < 0 || a >= int(ids.size()) ||
            b >= int(ids.size()) || !ids[a] || !ids[b]) return 4;
        ids.push_back(out.join(ids[a],ids[b]));
    }
    int root = 0;
    while (get(seq,a)) {
        if (in.n <= a && a < alph) {
            if (a != in.n + int(out.roots.size()) || !root) return 5;
            out.roots.push_back(root);
            root = 0;
        } else {
            if (a < 0 || a >= int(ids.size()) || !ids[a]) return 6;
            // Re-Pair's remaining start string must be expressed in binary unions.
            root = out.join(root, ids[a]);
        }
    }
    if (root || int(out.roots.size()) != in.m) return 7;
    out.write();
}