use std::collections::VecDeque; use proconio::input; fn main() { input! { n:usize, x:[[usize;n];n], a:[usize;n], } const INF: usize = std::usize::MAX; let mut ans = INF; for i in 0..1 << n { let mut g = vec![vec![]; n]; let mut out = vec![0; n]; for j in 0..n { for k in 0..n { if i & (1 << k) != 0 || x[j][k] == 0 { continue; } g[k].push(j); out[j] += 1; } } if is_dag(n, &g, &mut out) { ans = ans.min( (0..n) .map(|j| if i & (1 << j) != 0 { a[j] } else { 0 }) .sum::(), ); } } println!("{}", ans); } fn is_dag(n: usize, g: &Vec>, out: &mut Vec) -> bool { let mut q = VecDeque::new(); for i in 0..n { if out[i] == 0 { q.push_back(i); } } while let Some(crr) = q.pop_front() { for &nxt in g[crr].iter() { if out[nxt] == 0 { continue; } out[nxt] -= 1; if out[nxt] == 0 { q.push_back(nxt); } } } out.iter().all(|&out| out == 0) }