N人にN個の仕事を1つずつ割り当てます。それぞれの仕事をちょうど1回使い、割り当てコストの合計を最小化します。
ビットマスク動的計画法
dp[mask]を、maskでビットが立っている仕事を最初のInteger.bitCount(mask)人に割り当てたときの最小コストと定義します。次に割り当てる人のインデックスはInteger.bitCount(mask)です。まだ割り当てていない各仕事について、そのビットを立てて、その人のコストを加えます。
dp[mask | (1 << task)] = min(dp[mask | (1 << task)], dp[mask] + cost[person][task])。
空のマスクのコストは0、それ以外の状態の初期値はINFです。すべての仕事を割り当てた全ビットのマスクの値が答えです。このボトムアップ方式では、コストが0の状態もそのまま保持できます。N <= 20、各コストが最大1,000,000なので、割り当て全体のコストは最大20,000,000であり、INF = 1,000,000,000より小さくなります。
マスクは2^N個あり、各マスクから最大N個の遷移を調べるため、時間計算量はO(N * 2^N)、空間計算量はO(2^N)です。
Java
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
import java.io.BufferedInputStream;
import java.io.IOException;
public class Main {
private static final int INF = 1_000_000_000;
public static void main(String[] args) throws IOException {
FastScanner input = new FastScanner();
int n = input.nextInt();
int[][] cost = new int[n][n];
for (int person = 0; person < n; person++) {
for (int task = 0; task < n; task++) {
cost[person][task] = input.nextInt();
}
}
int stateCount = 1 << n;
int[] dp = new int[stateCount];
for (int mask = 1; mask < stateCount; mask++) {
dp[mask] = INF;
}
for (int mask = 0; mask < stateCount; mask++) {
int person = Integer.bitCount(mask);
if (person == n) {
continue;
}
for (int task = 0; task < n; task++) {
int taskBit = 1 << task;
if ((mask & taskBit) == 0) {
int nextMask = mask | taskBit;
dp[nextMask] = Math.min(
dp[nextMask],
dp[mask] + cost[person][task]
);
}
}
}
System.out.println(dp[stateCount - 1]);
}
private static class FastScanner {
private final BufferedInputStream input = new BufferedInputStream(System.in);
int nextInt() throws IOException {
int c;
do {
c = input.read();
} while (c <= ' ' && c != -1);
int value = 0;
while (c > ' ') {
value = value * 10 + c - '0';
c = input.read();
}
return value;
}
}
}