-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathOptimalAssignments.java
More file actions
71 lines (54 loc) · 2.07 KB
/
Copy pathOptimalAssignments.java
File metadata and controls
71 lines (54 loc) · 2.07 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
71
import java.util.*;
import java.io.*;
class Main {
public static List<Integer[]> permutations = new ArrayList<>();
public static Integer[] minPermutationsArr = new Integer[0];
public static Integer minCost = Integer.MAX_VALUE;
public static String OptimalAssignments(String[] strArr) {
// code goes here
Integer[][] matrix = new Integer[strArr.length][strArr.length];
minPermutationsArr = new Integer[matrix.lenght];
for (int i = 0; i < strArr.length; i++) {
String[] splitted = strArr[i].subString(1,strArr[i].length()-1).split(",");
for (int j = 0; j < splitted.length; j++) {
matrix[i][j] = Integer.parseInt(splitted[j]);
}
}
List<Integer> list = new ArrayList<>();
for (int i = 0; i < matrix.length; i++) {
list.add(i);
}
permute(list,0);
for (Integer[] permutation : permutations) {
int cost = 0;
for (int i = 0; i < permutation.length; i++) {
cost += matrix[i]permutation[i];
}
if (cost < minCost) {
minCost = cost;
minPermutationsArr = permutation;
}
}
String result = "";
for (int i = 0; i < minPermutationsArr.length; i++) {
result += "(" + (i + 1) + "-" + (minPermutationsArr[i]+1)+")";
}
return result;
}
static void permute(List<Integer> list, int k) {
for (int i = k; i < list.size(); i++) {
Collections.swap(list,i,k);
permute(list,k + 1);
Collections.swap(list,k,i);
}
if (k == list.size() -1) {
Integer[] arr = list.toArray(new Integer[list.size()]);
permutations.add(arr);
}
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(OptimalAssignments(s.nextLine()));
}
}