- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatching_Alt.java
More file actions
Latest commit
63 lines (52 loc) · 1.69 KB
/
Copy pathMatching_Alt.java
File metadata and controls
63 lines (52 loc) · 1.69 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
importjava.util.*;
importjava.io.*;
publicclassMatching_Alt {
publicstaticfinalintmod = 1000000007;
publicstaticintcount(intk) { // count number of ones in binary
intc = 0;
while (k > 0) {
k &= k - 1;
c++;
}
returnc;
}
publicstaticStringpad(Strings, intn) {
for (inti = s.length(); i < n; i++) {
s = "0" + s;
}
returns;
}
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
intn = Integer.parseInt(br.readLine());
String[] s;
boolean[][] matches = newboolean[n][n];
for (inti = 0; i < n; i++) {
s = br.readLine().split(" ");
for (intj = 0; j < n; j++)
matches[i][j] = Integer.parseInt(s[j]) == 1; // column = woman, row = man
}
int[][] dp = newint[n][(1 << n)];
for (inti = 0; i < n; i++)
dp[0][(1 << i)] = matches[i][0] ? 1 : 0; // last man left (think of as "there is about to be 0")
// i is women left, j is women bitmask --> 1 = available, 0 = taken
for (inti = 1; i < n; i++) {
for (intj = 0; j < (1 << n); j++) {
if (count(j) != i) // no point if #women left != bitmask #women left
continue;
for (intk = 0; k < n; k++) { // for every possible man
if (matches[k][i]) { // if the man and woman are compatible
if (((1 << k) & j) == 0) { // and if the woman has been taken in this bitmask
dp[i][j ^ (1 << k)] += dp[i - 1][j]; // where this woman is not taken +=
dp[i][j ^ (1 << k)] %= mod; //indices not matching; working in future: "there is about to be"
}
}
}
}
}
intans = 0;
for (inti = 0; i < (1 << n); i++)
ans = ans + dp[n - 1][i] % mod;
System.out.println(ans);
}
}