|
| 1 | +package BruteForce.P17471; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int N, ans = -1; |
| 9 | + static int[] nums; |
| 10 | + static ArrayList<Integer>[] graph; |
| 11 | + static boolean[] selected; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + System.setIn(new FileInputStream("src/BruteForce/P17471/input.txt")); |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + |
| 17 | + N = Integer.parseInt(br.readLine()); |
| 18 | + nums = new int[N+1]; |
| 19 | + graph = new ArrayList[N+1]; |
| 20 | + |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + for (int i = 1; i <= N; i++) nums[i] = Integer.parseInt(st.nextToken()); |
| 23 | + |
| 24 | + for (int i = 1; i <= N; i++) { |
| 25 | + graph[i] = new ArrayList<>(); |
| 26 | + st = new StringTokenizer(br.readLine()); |
| 27 | + int m = Integer.parseInt(st.nextToken()); |
| 28 | + while (m-- > 0) graph[i].add(Integer.parseInt(st.nextToken())); |
| 29 | + } |
| 30 | + |
| 31 | + selected = new boolean[N+1]; |
| 32 | + for (int i = 1; i <= N/2; i++) { |
| 33 | + dfs(1, 0, i); |
| 34 | + } |
| 35 | + |
| 36 | + System.out.println(ans); |
| 37 | + } |
| 38 | + |
| 39 | + static void dfs(int start, int cnt, int n) { |
| 40 | + if (cnt == n) { |
| 41 | + int[] A = new int[n], B = new int[N-n]; |
| 42 | + int a_cnt = 0, b_cnt = 0; |
| 43 | + for (int i = 1, j = 0, k = 0; i <= N; i++) { |
| 44 | + if (selected[i]) { A[j++] = i; a_cnt += nums[i]; } |
| 45 | + else { B[k++] = i; b_cnt += nums[i]; } |
| 46 | + } |
| 47 | + if (check(A) && check(B)) { |
| 48 | + int res = Math.abs(a_cnt - b_cnt); |
| 49 | + if (ans == -1) ans = res; |
| 50 | + else ans = Math.min(ans, res); |
| 51 | + } |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + for (int i = start; i <= N; i++) { |
| 56 | + selected[i] = true; |
| 57 | + dfs(i+1, cnt+1, n); |
| 58 | + selected[i] = false; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + static boolean check(int[] arr) { |
| 63 | + Queue<Integer> q = new LinkedList<>(); |
| 64 | + boolean[] visited = new boolean[N+1]; |
| 65 | + q.offer(arr[0]); |
| 66 | + visited[arr[0]] = true; |
| 67 | + |
| 68 | + while (!q.isEmpty()) { |
| 69 | + int p = q.poll(); |
| 70 | + for (int next : graph[p]) { |
| 71 | + boolean check = false; |
| 72 | + for (int a : arr) { |
| 73 | + if (next == a) { |
| 74 | + check = true; |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + if (check && !visited[next]) { |
| 79 | + visited[next] = true; |
| 80 | + q.offer(next); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + for (int a : arr) { |
| 85 | + if (!visited[a]) return false; |
| 86 | + } |
| 87 | + return true; |
| 88 | + } |
| 89 | +} |
0 commit comments