This repository was archived by the owner on Dec 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSW4012.java
More file actions
70 lines (56 loc) · 1.79 KB
/
SW4012.java
File metadata and controls
70 lines (56 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
public class SW4012 {
static int[][] map;
static boolean[] visited;
static int n;
static int min;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int test_case = 1; test_case <= tc; test_case++) {
min = Integer.MAX_VALUE;
n = sc.nextInt();
map = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = sc.nextInt();
}
}
visited = new boolean[n];
dfs(0, 0, 0);
System.out.println("#" + test_case + " " + min);
}
}
private static void dfs(int index, int v, int depth) {
if (depth == n/2) {
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < n; i++) {
if (visited[i]) {
for (int j = i; j < n; j++) {
if (visited[j]) {
sum1 += map[i][j] + map[j][i];
}
}
}
else {
for (int j = i; j < n; j++) {
if (!visited[j]) {
sum2 += map[i][j] + map[j][i];
}
}
}
}
min = Math.min(min, Math.abs(sum1 - sum2));
}
else {
for (int i = index; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
dfs(i + 1, i, depth + 1);
}
}
}
visited[v] = false;
}
}