【LeetCode 1349】 Maximum Students Taking Exam

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

题目描述

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());
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值