#include int bugs, patches, present[100], absent[100], fix[100], insert[100]; int time[100], all[1200000]; int abs(int a) { return a < 0 ? -a : a; } int apply(int bug, int patch, int depth) { int i; int oldbug = bug; if ((bug & absent[patch]) != 0 || (bug & (present[patch])) != present[patch]) return 0; bug = bug & (~fix[patch]); bug = bug | insert[patch]; if (all[bug] == -1 || all[bug] > (abs(all[oldbug]) + time[patch])) { if (depth < 1000) { all[bug] = all[oldbug] + time[patch]; for (i = 0; i < patches; i++) apply(bug, i, depth + 1); } else all[bug] = - (all[oldbug] + time[patch]); } return 0; } int main() { FILE *f; int i, j, k, kase = 1, start, done; char ch; f = fopen("bugs.in", "r"); fscanf(f, "%d %d", &bugs, &patches); while (bugs || patches) { for (i = 0; i < (1 << (bugs)); i++) all[i] = -1; for (i = 0; i < patches; i++) { fscanf(f, "%d", &time[i]); present[i] = absent[i] = fix[i] = insert[i] = 0; for (j = 0; j < bugs; j++) { absent[i] *= 2; present[i] *= 2; do { fscanf(f, "%c", &ch); } while (ch != '0' && ch != '+' && ch != '-'); if (ch == '-') absent[i]++; if (ch == '+') present[i]++; } for (j = 0; j < bugs; j++) { fix[i] *= 2; insert[i] *= 2; do { fscanf(f, "%c", &ch); } while (ch != '0' && ch != '+' && ch != '-'); if (ch == '-') fix[i]++; if (ch == '+') insert[i]++; } } start = (1 << (bugs)) - 1; all[start] = 0; for (i = 0; i < patches; i++) apply(start, i, 0); do { done = 1; for (i = 0; i < (1 << bugs); i++) { if (all[i] < -1) { all[i] = -all[i]; for (j = 0; j < patches; j++) apply(i, j, 0); done = 0; } } } while (!done); if (all[0] != -1) printf("Product %d\nFastest sequence takes %d seconds.\n\n", kase++, all[0]); else printf("Product %d\nBugs cannot be fixed.\n", kase++); fscanf(f, "%d %d", &bugs, &patches); } return 0; }