a1b88a02f6ea29e814d51775cd47fba84e7a4dca
1 import java
.util
.ArrayList
;
2 import java
.util
.LinkedList
;
3 import java
.util
.Collections
;
4 import java
.util
.Random
;
5 import java
.util
.Arrays
;
7 import java
.util
.Comparator
;
8 import java
.util
.AbstractMap
.SimpleEntry
;
9 import java
.util
.Comparator
;
10 import java
.util
.PriorityQueue
;
14 * Class that implements the pot problem solver.
16 * @author Mart Lubbers
18 public class LubbersSolver
implements IPetproblemSolver
{
20 public class Tuple
implements Comparable
<Tuple
>
25 public Tuple(int k
, int v
)
32 * Overrides compareTo so that the priorityqueue is ordered ascending
34 * @param a the entry to compare with
35 * @return comparison value
38 public int compareTo(Tuple a
)
40 //note that the values are swapped, so that the sort will be reversed
41 return Integer
.compare(a
.v
, this.v
);
45 public String
toString()
52 public int[] solve(int n
, int m
, int[][] compatibility
)
54 int[] result
= new int[n
];
56 // Set to -1 initially
57 for (int i
= 0; i
< result
.length
; i
++)
60 // Sum rows and columns
61 PriorityQueue
<Tuple
> row_sums
= new PriorityQueue
<Tuple
>(n
);
62 PriorityQueue
<Tuple
> col_sums
= new PriorityQueue
<Tuple
>(m
);
64 int[] running_row_sums
= new int[n
];
65 int[] running_col_sums
= new int[m
];
68 for (int j
= 0; j
< m
; j
++)
70 for (int i
= 0; i
< n
; i
++)
72 running_row_sums
[i
] += compatibility
[i
][j
];
73 running_col_sums
[j
] += compatibility
[i
][j
];
77 // Add running sums to queues
78 for (int i
= 0; i
< running_row_sums
.length
; i
++)
79 row_sums
.add(new Tuple(i
, running_row_sums
[i
]));
81 for (int i
= 0; i
< running_col_sums
.length
; i
++)
82 col_sums
.add(new Tuple(i
, running_col_sums
[i
]));
85 // Select smallest sum (in rows/cols)
86 // Get 1-indices for that sum's index
87 // Select smallest from those indices
88 while (!row_sums
.isEmpty() && !col_sums
.isEmpty()){
89 Tuple lowestIndexRow
= row_sums
.peek();
90 Tuple lowestIndexCol
= col_sums
.peek();
92 boolean useRow
= false;
94 if (lowestIndexRow
.v
< lowestIndexCol
.v
)
103 int smallestValue
= Integer
.MAX_VALUE
;
104 Tuple smallestKey
= null;
106 for (Tuple e
: col_sums
)
108 if (e
.v
< smallestValue
&& compatibility
[lowestIndexRow
.k
][e
.k
] == 1)
115 // No candidates in this list, continue
116 if (smallestKey
== null)
119 int col_index
= smallestKey
.k
;
120 col_sums
.remove(smallestKey
);
122 result
[lowestIndexRow
.k
] = col_index
;
129 int smallestValue
= Integer
.MAX_VALUE
;
130 Tuple smallestKey
= null;
132 for (Tuple e
: row_sums
)
134 if (e
.v
< smallestValue
&& compatibility
[e
.k
][lowestIndexCol
.k
] == 1)
141 // No candidates in this list, continue
142 if (smallestKey
== null)
145 int row_index
= smallestKey
.k
;
146 row_sums
.remove(smallestKey
);
148 result
[row_index
] = lowestIndexCol
.k
;
154 for (int i
= 0; i
< result
.length
; i
++)
155 score
+= result
[i
] == -1 ?
0 : 1;
157 System
.out
.println("Score: " + score
);