#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;

[[noreturn]] void finish(int code, const string &message) {
    cerr << (code == 0 ? "OK" : code == 1 ? "WA" : "FAIL") << ": " << message << '\n';
    exit(code);
}

int number(istream &f, int lo, int hi, int code, const string &where) {
    string s;
    if (!(f >> s)) finish(code, where + ": missing integer");
    int value = 0;
    for (char c : s) {
        if (c < '0' || c > '9') finish(code, where + ": invalid integer token");
        value = value * 10 + c - '0';
        if (value > hi) finish(code, where + ": integer out of range");
    }
    if (value < lo) finish(code, where + ": integer out of range");
    return value;
}

void no_extra(istream &f, int code, const string &name) {
    string s;
    if (f >> s) finish(code, name + ": extra token");
}

int gcd_local(int a, int b) {
    while (b) { int r = a % b; a = b; b = r; }
    return a;
}

vector<int> check(istream &f, const vector<int> &ns, int code, const string &name) {
    vector<int> fixed(ns.size());
    for (size_t tc = 0; tc < ns.size(); ++tc) {
        int n = ns[tc];
        vector<bool> seen(n + 1);
        string where = name + " case " + to_string(tc + 1);
        for (int i = 1; i <= n; ++i) {
            int v = number(f, 1, n, code, where + ", position " + to_string(i));
            if (seen[v]) finish(code, where + ": duplicate value " + to_string(v));
            seen[v] = true;
            if (i >= 2 && gcd_local(i, v) == 1) finish(code, where + ": gcd condition fails at " + to_string(i));
            fixed[tc] += (i == v);
        }
    }
    no_extra(f, code, name);
    return fixed;
}

int main(int argc, char **argv) {
    if (argc != 4) finish(3, "Usage: checker <input> <your_output> <reference_output>");
    ifstream input(argv[1], ios::binary), reference(argv[3], ios::binary);
    if (!input || !reference) finish(3, "Cannot open input or reference file");
    int t = number(input, 1, 10000, 3, "Input t"), total = 0;
    vector<int> ns(t);
    for (int &n : ns) {
        n = number(input, 2, 100000, 3, "Input n");
        if ((total += n) > 100000) finish(3, "Input: sum of n exceeds 100000");
    }
    no_extra(input, 3, "Input");
    vector<int> expected = check(reference, ns, 3, "Reference");
    ifstream output(argv[2], ios::binary);
    if (!output) finish(3, "Cannot open your output file");
    vector<int> actual = check(output, ns, 1, "Your output");
    for (int tc = 0; tc < t; ++tc) {
        string where = "Case " + to_string(tc + 1);
        if (actual[tc] < expected[tc]) finish(3, where + ": your output is better; reference is not optimal");
        if (actual[tc] > expected[tc]) finish(1, where + ": more fixed points than reference");
    }
    finish(0, "Valid permutations; fixed-point counts match the reference");
}
