// Session 88: bounded unknown-key search; exact paths for each supplied key.
// Compile: g++ -O3 -std=c++17 recovery_benchmark_engine.cpp -o recovery_engine
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>

constexpr int A=30, F=29, B=29;
constexpr double NEG=-1e290;

struct Path {
    double score=NEG;
    int end=0;
    std::vector<int> plain, skips;
};

struct Decoder {
    int period;
    bool selective;
    const std::vector<double>& logp;
    long long evaluations=0;
    double ll(int a,int b,int c) const {return logp[(a*A+b)*A+c];}
    int sid(int phase,int a,int b) const {return (phase*A+a)*A+b;}

    Path run(const std::vector<int>& cipher,const std::vector<int>& start,
             const std::vector<int>& finish,const std::vector<int>& key,
             int phase0,bool trace) {
        ++evaluations;
        const int n=cipher.size(), states=period*A*A;
        Path answer;
        if (!selective) {
            int phase=phase0,a=B,b=B;
            answer.score=0;
            for(int i=0;i<n;++i) {
                if(start[i]) a=b=B;
                int p=(cipher[i]-key[phase]+F)%F;
                answer.score+=ll(a,b,p);
                if(finish[i]) answer.score+=ll(b,p,B);
                if(trace) answer.plain.push_back(p);
                a=b;b=p;phase=(phase+1)%period;
            }
            answer.end=phase;return answer;
        }
        std::vector<double> current(states,NEG),next(states,NEG);
        std::vector<int> active{sid(phase0,B,B)},nextActive;
        current[active[0]]=0;
        std::vector<int> parents;
        std::vector<unsigned char> actions;
        if(trace) {parents.assign((size_t)n*states,-1);actions.resize((size_t)n*states);}
        const double fPenalty=std::log(.5);
        for(int i=0;i<n;++i) {
            for(int state:nextActive) next[state]=NEG;
            nextActive.clear();
            auto add=[&](int state,double score,int parent,bool skip) {
                if(next[state]==NEG) nextActive.push_back(state);
                if(score>next[state]+1e-12) {
                    next[state]=score;
                    if(trace) {parents[(size_t)i*states+state]=parent;actions[(size_t)i*states+state]=skip;}
                }
            };
            for(int state:active) {
                int phase=state/(A*A),a=(state/A)%A,b=state%A;
                if(start[i]) a=b=B;
                int p=(cipher[i]-key[phase]+F)%F;
                double normal=current[state]+ll(a,b,p)+(p==0?fPenalty:0);
                if(finish[i]) normal+=ll(b,p,B);
                add(sid((phase+1)%period,finish[i]?B:b,finish[i]?B:p),normal,state,false);
                if(cipher[i]==0) {
                    double skipped=current[state]+ll(a,b,0)+fPenalty;
                    if(finish[i]) skipped+=ll(b,0,B);
                    add(sid(phase,finish[i]?B:b,finish[i]?B:0),skipped,state,true);
                }
            }
            current.swap(next);active.swap(nextActive);
        }
        int best=-1;
        for(int state:active)
            if(best<0 || current[state]>current[best]+1e-12 ||
               (std::abs(current[state]-current[best])<=1e-12 && state<best)) best=state;
        if(best<0) throw std::runtime_error("No legal path");
        answer.score=current[best];answer.end=best/(A*A);
        if(trace) {
            answer.plain.resize(n);
            for(int i=n-1;i>=0;--i) {
                int parent=parents[(size_t)i*states+best];
                if(parent<0) throw std::runtime_error("Missing traceback parent");
                bool skip=actions[(size_t)i*states+best];
                answer.plain[i]=skip?0:(cipher[i]-key[parent/(A*A)]+F)%F;
                if(skip) answer.skips.push_back(i);
                best=parent;
            }
            std::reverse(answer.skips.begin(),answer.skips.end());
        }
        return answer;
    }
};

template<class T> void array_json(const std::vector<T>& a) {
    std::cout<<'[';
    for(size_t i=0;i<a.size();++i) {if(i)std::cout<<',';std::cout<<a[i];}
    std::cout<<']';
}
void path_json(const Path& p) {
    std::cout<<"{\"score\":"<<p.score<<",\"end_phase\":"<<p.end<<",\"plaintext\":";
    array_json(p.plain);std::cout<<",\"skips\":";array_json(p.skips);std::cout<<'}';
}

int main() {
    try {
        std::string mode;
        int n,cut,period,restarts,sweeps,selective,phase0;
        unsigned seed;
        if(!(std::cin>>mode>>n>>cut>>period>>restarts>>sweeps>>seed>>selective>>phase0)) return 2;
        std::vector<int> cipher(n),start(n),finish(n);
        std::vector<double> table(A*A*A),uni(F);
        for(auto& x:cipher)std::cin>>x;
        for(auto& x:start)std::cin>>x;
        for(auto& x:finish)std::cin>>x;
        for(auto& x:table)std::cin>>x;
        for(auto& x:uni)std::cin>>x;
        if(!std::cin || cut<1 || cut>n || period<1 || period>29 || !finish[cut-1])
            throw std::runtime_error("Invalid input or non-word cut");
        std::vector<int> c(cipher.begin(),cipher.begin()+cut),s(start.begin(),start.begin()+cut),e(finish.begin(),finish.begin()+cut);
        Decoder decoder{period,(bool)selective,table};
        std::vector<int> bestKey(period,0);double bestScore=NEG;int winning=-1;
        if(mode=="oracle") {
            for(auto& k:bestKey)std::cin>>k;
            if(!std::cin) throw std::runtime_error("Missing oracle key");
            bestScore=decoder.run(c,s,e,bestKey,phase0,false).score;
        } else if(mode=="fit") {
            if(phase0!=0) throw std::runtime_error("Unknown-key fitting starts at phase zero");
            std::mt19937 rng(seed);
            std::uniform_int_distribution<int> drawKey(0,F-1);
            std::vector<int> init(period,0),order(period);std::iota(order.begin(),order.end(),0);
            for(int phase=0;phase<period;++phase) {
                double top=NEG;
                for(int k=0;k<F;++k) {
                    double score=0;
                    for(int i=phase;i<cut;i+=period)score+=uni[(c[i]-k+F)%F];
                    if(score>top+1e-12){top=score;init[phase]=k;}
                }
            }
            for(int restart=0;restart<restarts;++restart) {
                std::vector<int> key=init;
                if(restart)for(auto& k:key)k=drawKey(rng);
                double current=decoder.run(c,s,e,key,0,false).score;
                for(int pass=0;pass<sweeps;++pass) {
                    std::shuffle(order.begin(),order.end(),rng);bool changed=false;
                    for(int slot:order) {
                        int original=key[slot],choice=original;double top=current;
                        for(int k=0;k<F;++k) {
                            if(k==original)continue;
                            key[slot]=k;double score=decoder.run(c,s,e,key,0,false).score;
                            if(score>top+1e-10){top=score;choice=k;}
                        }
                        key[slot]=choice;
                        if(choice!=original)changed=true;
                        current=top;
                    }
                    if(!changed)break;
                }
                if(current>bestScore+1e-10){bestScore=current;bestKey=key;winning=restart;}
            }
        } else throw std::runtime_error("Unknown mode");
        Path prefix=decoder.run(c,s,e,bestKey,phase0,true);
        if(std::abs(prefix.score-bestScore)>1e-7)throw std::runtime_error("Score replay differs");
        std::vector<int> cc(cipher.begin()+cut,cipher.end()),ss(start.begin()+cut,start.end()),ee(finish.begin()+cut,finish.end());
        Path suffix=decoder.run(cc,ss,ee,bestKey,prefix.end,true);
        std::cout<<std::setprecision(17)<<"{\"key\":";array_json(bestKey);
        std::cout<<",\"winning_restart\":"<<winning<<",\"evaluations\":"<<decoder.evaluations<<",\"prefix\":";
        path_json(prefix);std::cout<<",\"suffix\":";path_json(suffix);std::cout<<"}\n";
        return 0;
    } catch(const std::exception& error) {std::cerr<<error.what()<<'\n';return 1;}
}
