|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int n; |
| 7 | + static int[] people; |
| 8 | + static List<Integer>[] graph; |
| 9 | + static boolean[] selected; |
| 10 | + static int res; |
| 11 | + static int INF = 987654321; |
| 12 | + |
| 13 | + public static void main(String[] args) throws IOException { |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + StringTokenizer st; |
| 16 | + n = Integer.parseInt(br.readLine()); |
| 17 | + people = new int[n + 1]; |
| 18 | + graph = new ArrayList[n + 1]; |
| 19 | + selected = new boolean[n + 1]; |
| 20 | + |
| 21 | + res = INF; |
| 22 | + |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + for (int i = 1; i <= n; i++) { |
| 25 | + people[i] = Integer.parseInt(st.nextToken()); |
| 26 | + graph[i] = new ArrayList<>(); |
| 27 | + } |
| 28 | + |
| 29 | + for (int i = 1; i <= n; i++) { |
| 30 | + st = new StringTokenizer(br.readLine()); |
| 31 | + int cnt = Integer.parseInt(st.nextToken()); |
| 32 | + for (int j = 0; j < cnt; j++) { |
| 33 | + graph[i].add(Integer.parseInt(st.nextToken())); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + dfs(1); |
| 38 | + if(res==INF){ |
| 39 | + System.out.println(-1); |
| 40 | + } |
| 41 | + else{ |
| 42 | + System.out.println(res); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + static void dfs(int idx) { |
| 47 | + if (idx == n + 1) { |
| 48 | + List<Integer> a = new ArrayList<>(); |
| 49 | + List<Integer> b = new ArrayList<>(); |
| 50 | + |
| 51 | + for (int i = 1; i <= n; i++) { |
| 52 | + if (selected[i]) a.add(i); |
| 53 | + else b.add(i); |
| 54 | + } |
| 55 | + |
| 56 | + if (a.isEmpty() || b.isEmpty()) return; |
| 57 | + |
| 58 | + if (checked(a) && checked(b)) { |
| 59 | + int diff = Math.abs(sum(a) - sum(b)); |
| 60 | + res = Math.min(res, diff); |
| 61 | + } |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + selected[idx] = true; |
| 66 | + dfs(idx + 1); |
| 67 | + |
| 68 | + selected[idx] = false; |
| 69 | + dfs(idx + 1); |
| 70 | + } |
| 71 | + |
| 72 | + static boolean checked(List<Integer> area) { |
| 73 | + if (area.isEmpty()) return false; |
| 74 | + |
| 75 | + Queue<Integer> q = new LinkedList<>(); |
| 76 | + boolean[] visited = new boolean[n + 1]; |
| 77 | + q.add(area.get(0)); |
| 78 | + visited[area.get(0)] = true; |
| 79 | + int cnt = 1; |
| 80 | + |
| 81 | + while (!q.isEmpty()) { |
| 82 | + int now = q.poll(); |
| 83 | + for (int next : graph[now]) { |
| 84 | + if (!visited[next] && area.contains(next)) { |
| 85 | + visited[next] = true; |
| 86 | + q.add(next); |
| 87 | + cnt++; |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return cnt == area.size(); |
| 93 | + } |
| 94 | + |
| 95 | + static int sum(List<Integer> area) { |
| 96 | + int s = 0; |
| 97 | + for (int x : area) s += people[x]; |
| 98 | + return s; |
| 99 | + } |
| 100 | +} |
| 101 | +``` |
0 commit comments