use std::cmp::*; use std::collections::*; // https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes.by_ref().map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr,) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error")); } /** * Union-Find tree. * Verified by https://atcoder.jp/contests/pakencamp-2019-day3/submissions/9253305 */ struct UnionFind { disj: Vec, rank: Vec } impl UnionFind { fn new(n: usize) -> Self { let disj = (0..n).collect(); UnionFind { disj: disj, rank: vec![1; n] } } fn root(&mut self, x: usize) -> usize { if x != self.disj[x] { let par = self.disj[x]; let r = self.root(par); self.disj[x] = r; } self.disj[x] } fn unite(&mut self, x: usize, y: usize) { let mut x = self.root(x); let mut y = self.root(y); if x == y { return } if self.rank[x] > self.rank[y] { std::mem::swap(&mut x, &mut y); } self.disj[x] = y; self.rank[y] += self.rank[x]; } #[allow(unused)] fn is_same_set(&mut self, x: usize, y: usize) -> bool { self.root(x) == self.root(y) } #[allow(unused)] fn size(&mut self, x: usize) -> usize { let x = self.root(x); self.rank[x] } } fn is_conn(bits: i32) -> bool { let mut uf = UnionFind::new(25); for i in 0..5 { for j in 0..4 { let v = i * 5 + j; if (bits & 3 << v) == (3 << v) { uf.unite(v, v + 1); } } } for i in 0..4 { for j in 0..5 { let v = i * 5 + j; if (bits & 33 << v) == (33 << v) { uf.unite(v, v + 5); } } } let mut tmp = 25; for i in 0..25 { if (bits & 1 << i) == 0 { continue; } let r = uf.root(i); if tmp == 25 { tmp = r; } else if tmp != r { return false; } } true } fn main() { input!(c: [i64; 25]); let s: i64 = c.iter().sum(); let mut mi = 1i64 << 50; let mut is_conn = vec![false; 1 << 25]; let mut que = VecDeque::new(); for i in 0..25 { que.push_back(1 << i); } while let Some(v) = que.pop_front() { if is_conn[v] { continue; } is_conn[v] = true; for i in 0..25 { if (v & 1 << i) != 0 { continue; } let mut mask = (5 << (i % 5)) >> 1 << (i / 5 * 5); if i >= 5 { mask |= 1 << (i - 5); } mask |= 1 << (i + 5); if (v & mask) != 0 { let new = v | 1 << i; if is_conn[new] { continue; } que.push_back(new); } } } for bits in 1..1 << 24 { if is_conn[bits] && is_conn[(1 << 25) - 1 - bits] { let mut tmp = s; for i in 0..25 { if (bits & 1 << i) != 0 { tmp -= 2 * c[i]; } } mi = min(mi, tmp.abs()); } } println!("{}", mi); }