题目描述
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:
Input: seats = [["#",".","#","#",".","#"],
[".","#","#","#","#","."],
["#",".","#","#",".","#"]]
Output: 4
Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam.
Example 2:
Input: seats = [[".","#"],
["#","#"],
["#","."],
["#","#"],
[".","#"]]
Output: 3
Explanation: Place all students in available seats.
Example 3:
Input: seats = [["#",".",".",".","#"],
[".","#",".","#","."],
[".",".","#",".","."],
[".","#",".","#","."],
["#",".",".",".","#"]]
Output: 10
Explanation: Place students in available seats in column 1, 3 and 5.
Constraints:
seats contains only characters ‘.’ and’#’.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8
思路
动态规划
当前行的状态之和上一行有关,用二进制表示上一行和当前行的状态,dp[i][s] = max(dp[i][s], dp[i-1][l]+__builtin_popcount(s)) ( l 和 s 遍历所有状态)
代码
class Solution {
public:
int maxStudents(vector<vector<char>>& seats) {
const int m = seats.size();
const int n = seats[0].size();
vector<int> s(m+1);
for (int i=1; i<=m; ++i) {
for (int j=0; j<n; ++j) {
s[i] |= (seats[i-1][j] == '#') << j;
}
}
vector<vector<int>> dp(m+1, vector<int>(1<<n));
for (int i=1; i<=m; ++i) {
for (int c=0; c<(1<<n); ++c) {
if (c & (c>>1) || c & s[i]) continue;
for (int l=0; l<(1<<n); ++l) {
if (l & s[i-1] || l & (c>>1) || c & (l>>1)) continue;
dp[i][c] = max(dp[i][c], dp[i-1][l] + __builtin_popcount(c));
}
}
}
return *max_element(dp[m].begin(), dp[m].end());
}
};

本文探讨了一个有趣的问题:如何在教室中最大化学生座位安排,同时防止考试作弊。通过动态规划算法,我们分析了不同教室布局下,如何在考虑座位损坏的情况下,使尽可能多的学生参加考试而不发生作弊行为。文章提供了详细的算法思路和C++代码实现。
478

被折叠的 条评论
为什么被折叠?



