Leetcode1349:参加考试的最大学生数(动态规划+状态压缩+位运算)

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.

Leetcode1349:参加考试的最大学生数(动态规划+状态压缩+位运算)

Constraints:

seats contains only characters '.' and'#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8

动态规划+状态压缩+位运算

class Solution {
public:
    int maxStudents(vector<vector<char>>& seats) {
        int rows=seats.size(),cols=seats[0].size();
        vector<vector<int>> dp(rows+1,vector<int>(1<<cols,0));
        for(int i=1;i<=rows;i++){
            for(int j=0;j<(1<<cols);j++){
                bitset<8> bs(j);
                bool ok=true;
                for(int k=0;k<cols;k++){
                    if(bs[k]&&seats[i-1][k]=='#') ok=false;
                }
                if(((j>>1)&j)||((j<<1)&j)) ok=false;
                if(!ok){
                    dp[i][j]=-1;
                    continue;
                }
                for(int l=0;l<(1<<cols);l++){
                    if(dp[i-1][l]==-1||((l>>1)&j)||((l<<1)&j)) continue;
                    dp[i][j]=max(dp[i][j],dp[i-1][l]+(int)bs.count());
                }
            }
        }
        return *max_element(dp[rows].begin(),dp[rows].end());
    }
};

Leetcode1349:参加考试的最大学生数(动态规划+状态压缩+位运算)

上一篇:1069 微博转发抽奖 (20分)主要思路,测试点3分析


下一篇:深入理解overlayfs(二):使用与原理分析(转载)