其他分享
首页 > 其他分享> > Leetcode1349:参加考试的最大学生数(动态规划+状态压缩+位运算)

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.

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());
    }
};

标签:upper,参加考试,right,运算,Leetcode1349,int,see,vector,seats
来源: https://blog.csdn.net/weixin_40903417/article/details/122770700