|
| 1 | +This is a DP question with bitmasks. |
| 2 | + |
| 3 | +Let's say there are only 5 people. |
| 4 | +We will have a binary string where the i-th bit = 1, if the i-th subject has been allocated, and 0 if it hasn't. |
| 5 | + |
| 6 | +Now, let's say we have found the number of assignments for 4 people. |
| 7 | + |
| 8 | +5th person' subjects are - 1 0 0 1 0 |
| 9 | + |
| 10 | +Then, f(5, 11111) = f(4, 01111) + f(4, 11101) |
| 11 | + |
| 12 | +That is, the options are, we must allocate 4 subjects to the first 4 people in either - 01111 or 11101. |
| 13 | + |
| 14 | +This takes us to our recurrence. |
| 15 | + |
| 16 | +f(i, mask) represents the number of assignments to the first i students where the i-th subject is allocated if it is set in the mask. |
| 17 | + |
| 18 | +f(0, 0) = 1 |
| 19 | + |
| 20 | +f(i + 1, mask) = f(i - 1, mask with j-th bit unset) = f(i, XOR(mask, 2^(j - 1))), where j is a subject that student i likes. and mask has exactly i bits set. |
| 21 | + |
| 22 | +Psuedo-code |
| 23 | + |
| 24 | +for i = 1... .n |
| 25 | + for mask 1 ... 2^n - 1 |
| 26 | + if(mask has i bits set) |
| 27 | + for(j = 1 ... n) |
| 28 | + if(student i likes subject j, then) |
| 29 | + f(i, mask) += f(i - 1, mask without j-th bit set). |
| 30 | + |
| 31 | +For convenience, f(0, 0) = 1 |
| 32 | + |
| 33 | +f(N, 11 .... 1) is the answer = f(N, 2^N - 1) |
| 34 | + |
| 35 | +------------------------------------------------------------------ |
| 36 | + |
| 37 | +int bit_set(int mask, int position) |
| 38 | +{ |
| 39 | + position--; |
| 40 | + return (mask & (1 << position) ); |
| 41 | +} |
| 42 | + |
| 43 | +int one_bit_unset(int mask, int position) |
| 44 | +{ |
| 45 | + position--; |
| 46 | + return (mask^(1 << position) ); |
| 47 | +} |
| 48 | + |
| 49 | +void solve() |
| 50 | +{ |
| 51 | + int no_of_students; |
| 52 | + scanf("%d", &no_of_students); |
| 53 | + |
| 54 | + int likes[no_of_students + 1][no_of_students + 1]; |
| 55 | + for(int i = 1; i <= no_of_students; i++) |
| 56 | + for(int j = 1; j <= no_of_students; j++) |
| 57 | + scanf("%d", &likes[i][j]); |
| 58 | + |
| 59 | + memset(no_of_assignments, 0, sizeof(no_of_assignments)); |
| 60 | + no_of_assignments[0][0] = 1; |
| 61 | + |
| 62 | + for(int i = 1; i <= no_of_students; i++) |
| 63 | + { |
| 64 | + for(int mask = 1; mask < (1 << no_of_students); mask++) |
| 65 | + { |
| 66 | + if(population_count[mask] == i) |
| 67 | + { |
| 68 | + for(int j = 1; j <= no_of_students; j++) |
| 69 | + { |
| 70 | + if(bit_set(mask, j) && likes[i][j]) |
| 71 | + no_of_assignments[i][mask] += no_of_assignments[i - 1][one_bit_unset(mask, j)]; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + printf("%lld\n", no_of_assignments[no_of_students][(1 << no_of_students) - 1]); |
| 78 | +} |
| 79 | + |
0 commit comments