import std.stdio, std.array, std.string, std.conv, std.algorithm; import std.typecons, std.range, std.random, std.math, std.container; import std.numeric, std.bigint, core.bitop, core.stdc.stdlib, std.datetime; void main() { auto N = readln.chomp.to!int; auto A = readln.split.map!(to!int).array; auto B = A.split(2); int[][] C; foreach (b; B) { if (b.empty) continue; C ~= new int[](2); C.back[0] = b.count(0).to!int; C.back[1] = b.count(1).to!int; } auto M = C.length.to!int; auto dp = new int[][](M+1, N*2); foreach (i; 0..M+1) dp[i][] = 1 << 29; dp[0][0] = 0; int zero_sum = 0; int one_sum = 0; foreach (i; 0..M) { int zero = C[i][0]; int one = C[i][1]; foreach (zero_used; 0..N+1) { int one_used = zero_sum + one_sum - zero_used; int zero_amari = max(0, zero_sum - zero_used); dp[i+1][zero_used+zero+one] = min(dp[i+1][zero_used+zero+one], dp[i][zero_used] + max(0, one - zero_amari)); int one_amari = max(0, one_sum - one_used); dp[i+1][zero_used] = min(dp[i+1][zero_used], dp[i][zero_used] + max(0, zero - one_amari)); } zero_sum += C[i][0]; one_sum += C[i][1]; } auto ans = dp[M][A.count(0).to!int]; if (ans == 1 << 29) { writeln(-1); } else { writeln(ans); } }