bool debug = false; #include #include using namespace std; constexpr int kN = 1 << 18, kInf = int(1E9 + 10), kC = 18; int a[kC], g[kC][kC], dp[kN], cost, n, d[kC], td[kC]; bool have[kC], used[kC]; bool ok() { queue q; int nxt; for (int i = 0; i < n; i++) used[i] = have[i] | (d[i] == 0); for (int i = 0; i < n; i++) if (used[i]) q.push(i); for (int i = 0; i < n; i++) td[i] = d[i]; while (!q.empty()) { nxt = q.front(); q.pop(); for (int i = 0; i < n; i++) if (g[i][nxt]) td[i]--; for (int i = 0; i < n; i++) if (td[i] == 0 && !used[i]) { used[i] = true; q.push(i); } } if (debug) { printf("--debug--\n"); for (int i = 0; i < n; i++) printf("%d", have[i] ? 1 : 0); printf("\n"); for (int i = 0; i < n; i++) printf("%d", used[i] ? 1 : 0); printf("\n\n"); } for (int i = 0; i < n; i++) if (!used[i]) return false; return true; } int dfs(int pos) { if (ok()) return cost; if (pos >= n) return kInf; int ans = kInf; for (int i = pos; i < n; i++) { have[i] = true; cost += a[i]; ans = min(ans, dfs(i + 1)); have[i] = false; cost -= a[i]; } return ans; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &g[i][j]); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) d[i] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (g[i][j] == 1) d[i]++; cost = 0; for (int i = 0; i < n; i++) have[i] = false; printf("%d\n", dfs(0)); }