#include #include #include #include #include #define _USE_MATH_DEFINES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3fLL; const double EPS = 1e-8; const int MOD = 1000000007; // const int MOD = 998244353; const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1}; // const int dy[] = {1, 1, 0, -1, -1, -1, 0, 1}, // dx[] = {0, -1, -1, -1, 0, 1, 1, 1}; struct IOSetup { IOSetup() { cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << fixed << setprecision(20); cerr << fixed << setprecision(10); } } iosetup; /*-------------------------------------------------*/ using CostType = long long; struct Edge { int src, dst; CostType cost; Edge(int src, int dst, CostType cost = 0) : src(src), dst(dst), cost(cost) {} inline bool operator<(const Edge &rhs) const { return cost != rhs.cost ? cost < rhs.cost : dst != rhs.dst ? dst < rhs.dst : src < rhs.src; } inline bool operator<=(const Edge &rhs) const { return !(rhs < *this); } inline bool operator>(const Edge &rhs) const { return rhs < *this; } inline bool operator>=(const Edge &rhs) const { return !(*this < rhs); } }; vector topological_sort(const vector > &graph) { int n = graph.size(); vector deg(n, 0); REP(i, n) { for (const Edge &e : graph[i]) ++deg[e.dst]; } queue que; REP(i, n) { if (deg[i] == 0) que.emplace(i); } vector res; while (!que.empty()) { int ver = que.front(); que.pop(); res.emplace_back(ver); for (const Edge &e : graph[ver]) { if (--deg[e.dst] == 0) que.emplace(e.dst); } } return res.size() == n ? res : vector(); }; int main() { int n; cin >> n; vector > x(n, vector(n)); REP(i, n) REP(j, n) cin >> x[i][j]; vector a(n); REP(i, n) cin >> a[i]; int ans = accumulate(ALL(a), 0); REP(i, (1 << n) - 1) { vector conf(n, false); REP(j, n) if (i >> j & 1) conf[j] = true; vector > graph(n); REP(i, n) { if (conf[i]) continue; REP(j, n) { if (x[i][j] == 1) graph[j].emplace_back(j, i); } } vector ts = topological_sort(graph); if (ts.empty()) continue; bool cruel = true; REP(j, n) { int now = ts[j]; if (conf[now]) continue; bool prop = false; REP(k, n) { if (x[now][k] == 1 && !conf[k]) prop = true; } if (prop) { cruel = false; break; } conf[now] = true; } if (cruel) { int tmp = 0; REP(j, n) if (i >> j & 1) tmp += a[j]; ans = min(ans, tmp); } } cout << ans << '\n'; return 0; }