Hi
Regarding the problem 13.10, which is to find a minimum sequential subcover, when the set of string to match is made of distinct elements: what I came up with only uses trivial data structures, unlike the proposed solution which is quite elaborate.
Since I have rather limited faith in my guru-ness I though I’ll post it up here with a test driver and wait to hear what I overlooked. It may be that the authors skipped over this solution because of the string comparison adding a factor O(max len(s)), s in Q to the time complexity (but then again, on a hash hit, the strings are also compared to test for spurious hits, no ?).
Edit 1 : The faulty condition on subcover index update was edited to reflect the discussion further down.
Edit 2 : This solution is incorrect, see discussion further down
Thanks.
pair<int, int> Prob13_10(const vector<string> &Q, const vector<string> &A) {
pair<int, int> min_idx(-1, -1);
int l = -1, r = 0;
int next_match = 0;
while (r != A.size()) {
while (r != A.size() && next_match < Q.size()) {
bool reduce_left = (Q.size() > 1 && next_match == 1 && A[r] == Q[0]);
if (A[r] == Q[next_match] ||reduce_left) {
if (next_match==0 || reduce_left)
l = r;
if (!reduce_left)
next_match++;
}
r++;
}
/* The next condition is wrong, see explanations further down
if (min_idx.first == -1 || r -1- l < min_idx.second - min_idx.first)
min_idx = make_pair(l, r - 1);*/
if (next_match==Q.size()&&(min_idx.first == -1 || r -1- l < min_idx.second - min_idx.first))
min_idx = make_pair(l, r - 1);
next_match = 0;
l = r;
}
return min_idx;
}
void Prob13_10D() {
string declaration("My paramount object in this struggle is to save the Union , and is not either to save or to destroy slavery . If I could save the Union without freeing any slave I would do it , and if I could save it by freeing all the slaves I would do it ; and if I could save it by freeing some and leaving others alone I would also do that");
string buf;
stringstream ss(declaration);
vector<string> A,Q;
while (ss >> buf)
A.push_back(buf);
Q.push_back("Union"); Q.push_back("save");
pair<int, int> min = Prob13_10(Q, A);
assert(min.first == 10 && min.second == 17);
A.clear(); Q.clear();
A.push_back("a"); A.push_back("a"); A.push_back("a"); A.push_back("a"); A.push_back("b"); A.push_back("c");
Q.push_back("a"); Q.push_back("c");
min = Prob13_10(Q, A);
assert(min.first == 3 && min.second == 5);
Q = { "0", "2", "9", "4", "6" };
A = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "2", "4", "6", "10", "10", "10", "3", "2", "1", "0" };
min = Prob13_10(Q, A);
assert(min.first == 0 && min.second == 12);
}