leetcode-1349-Maximum Students Taking Exam
问题
Given a m * n
matrix seats
that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#'
character otherwise it is denoted by a '.'
character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
Example 1:
1 | Input: seats = [["#",".","#","#",".","#"], |
Example 2:
1 | Input: seats = [[".","#"], |
Example 3:
1 | Input: seats = [["#",".",".",".","#"], |
Constraints:
seats
contains only characters'.' and``'#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8
分析
使用状态压缩的DP算法进行逐行处理, f[i][j] 表示第 i 行的安排为 j 状态时前 i 排能够最多安排多少学生。其中 j 使用二进制数进行表示,如 10000001 表示该行的第一个位置和最后一个位置安排学,其他位置不安排学生。有状态转移方程。
$$
f[i][j] = max\{f[i-1][k]\} + popcnt(j) \; (j\&position[i] == j \;\&\& \;j|k \in S)
$$
其中 popcnt(j) 表示计算出 j 的二进制表示中 bit 位是1的个数,position[i] 表示第 i 行中由于椅子好坏的原因允许安排学生的情况,如第 i。行为,["#",".","#","#",".","#"]
,则 position[i] 为 010010
,集合 S 表示所有的二进制表示中没有两个相邻的bit是1的集合。
目标:$ max\{f[n-1][]\}$,
初始条件 $f[0][k] == popcnt(k) \; (k\&position[0] == k \; \&\& \;k \in S)$,其他 $ f[i][j] = -INF$。
代码
1 | // 0 ms |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/06/leetcode-1349/
License: 知识共享署名-非商业性使用 4.0 国际许可协议