#include #include #include #include string makestr(char *c, int n) { string i; for (int j = 0; j < n; j++) i += string(c); return i; } int main (int c, char **v) { ifstream in ("bugs.in"); int bugs, patches, nr = 0; while ((in >> bugs >> patches), (bugs != 0 || patches != 0)) { int *pattime = new int[patches]; string *patpre = new string[patches]; string *patfix = new string[patches]; for (int i = 0; i < patches; i++) in >> pattime[i] >> patpre[i] >> patfix[i]; vector bug; vector bugtime; vector bugdone; bug.push_back(makestr ("+", bugs)); bugtime.push_back (0); int donetime = 0; int bugfound; string donestr = makestr ("-", bugs); while (bug.size()) { bugfound = 0; for (unsigned int i = 0; i < bug.size(); i++) { if (bugtime[i] < bugtime[bugfound]) bugfound = i; } int i = bugfound; for (int pat = 0; pat < patches; pat++) { int ok = 1; for (int j = 0; j < bugs; j++) { if (patpre[pat][j] != '0' && patpre[pat][j] != bug[i][j]) ok = 0; } if (!ok) continue; string newbug = bug[i]; int newtime = bugtime[i] + pattime[pat]; if (newtime >= donetime && donetime) continue; for (int j = 0; j < bugs; j++) if (patfix[pat][j] != '0') newbug[j] = patfix[pat][j]; ok = 1; for (unsigned int is = 0; is < bug.size(); is++) { if (bug[is] == newbug) { ok = 0; if (bugtime[is] > newtime) bugtime[is] = newtime; } } for (unsigned int is = 0; is < bugdone.size(); is++) if (bugdone[is] == newbug) ok = 0; if (!ok) continue; if (newbug == donestr) { if (!donetime || donetime > newtime) donetime = newtime; } else { bug.push_back (newbug); bugtime.push_back (newtime); } } bugdone.push_back (bug[i]); bugtime.erase (bugtime.begin() + i); bug.erase (bug.begin () + i); } cout << "Product " << ++nr << endl; if (donetime) { cout << "Fastest sequence takes " << donetime << " seconds." << endl; } else cout << "Bugs cannot be fixed." << endl; cout << endl; } }