The Longest Prefix

prefix

C++

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>

using namespace std;

bool compstr(string & str, string & pattern, int start){
    for (int i=0; i<pattern.size(); ++i){
        if (i+start > str.size()-1){
            return false;
        }
        if (str[i+start] != pattern[i]){
            return false;
        }
    }
    return true;
}

int run(vector<string> patterns, string str){
    int strlen = str.size();
    int lenpat = patterns.size();
    bool cont = true;
    vector<int> gen(lenpat,0);
    vector<int> lens;
    for (auto p:patterns){
        lens.push_back(p.size());
    }
    while (cont == true){
        vector<int> nextGen = gen;
        bool found = false;
        for (int p2 = 0; p2 < lenpat; ++p2){
            for (int p = 0; p < lenpat; ++p){
                int genp2 = gen[p2];
                int genlen = genp2 + lens[p];
                if (compstr(str, patterns[p], genp2)){
                    if (nextGen[p] < genlen){
                        nextGen[p] = genlen;
                        found = true;
                        if (nextGen[p] >= strlen){
                            cont = false;
                        }
                    }
                }
            }
        }
        if (!found){
            cont = false;
        }
        gen = nextGen;
    }
    return *max_element(gen.begin(),gen.end());
}

int main(){
    ifstream fIn;
    fIn.open("prefix.in");
    string p;
    vector<string> patterns;
    string s;
    while (true){
        fIn >> p;
        if (p == ".") {
            break;
        }
        patterns.push_back(p);
    }
    stringstream ss;
    while(!fIn.eof()) {
        string s1;
        fIn >> s1;
        ss << s1;
    }
    s = ss.str();
    fIn.close();

    int res = run(patterns,s);

    ofstream fOut;
    fOut.open("prefix.out");
    fOut << res << endl;
    fOut.close();

    cout << res << endl;

    return 0;
}