package _0943; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class Main { private int n; private int[][] x; private int[] a; public void solve(BufferedReader stdin, PrintWriter stdout) throws NumberFormatException, IOException { Pattern space = Pattern.compile(" "); n = Integer.parseInt(stdin.readLine()); x = new int[n][n]; for (int i = 0; i < n; i++) { x[i] = space.splitAsStream(stdin.readLine()).mapToInt(Integer::parseInt).toArray(); } a = space.splitAsStream(stdin.readLine()).mapToInt(Integer::parseInt).toArray(); int bit = 0; for (int i = 0; i < n; i++) { if (Arrays.stream(x[i]).allMatch(v -> v == 0)) { bit |= 1 << i; } } stdout.println(f(bit, 0)); } private Map cache = new HashMap<>(); private int f(int b1, int b2) { if (b1 == (1 << n) - 1) { return 0; } Tuple t = new Tuple(); t.x = b1; t.y = b2; if (cache.containsKey(t)) { return cache.get(t); } int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if ((b1 & (1 << i)) != 0) { continue; } int c1 = b1 | (1 << i); int c2 = b2; int d = 0; for (int j = 0; j < n; j++) { if (x[i][j] == 1 && (b1 & (1 << j)) == 0 && (b2 & (1 << j)) == 0) { c2 |= 1 << j; d += a[j]; } } ans = Math.min(ans, f(c1, c2) + d); } cache.put(t, ans); return ans; } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); PrintWriter stdout = new PrintWriter(System.out, false); new Main().solve(stdin, stdout); stdout.flush(); } private static class Tuple { private int x; private int y; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tuple other = (Tuple) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } }