1349. Maximum Students Taking Exam(DP,状态压缩)
Posted dacc123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1349. Maximum Students Taking Exam(DP,状态压缩)相关的知识,希望对你有一定的参考价值。
- Maximum Students Taking Exam
Add to List
Share
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.
题意:上图中,#表示坏掉的椅子,.表示好的椅子,在椅子上安排考试,不能让学生作弊
题解:用二进制,表示每一行的每种安排的可能性。然后再进行动态规划,dp[i][j] = max{dp[i-1][k]+num[j]} 其中j 表示第i行的某个安排的二进制数,k同理是i-1行的某个安排,k和j满足不作弊的条件。num[j]表示j安排下,坐了多少学生。由于数组长度最多为8,所以状态数组的第二个维度最多为2^8-1,
class Solution {
public:
int n,m;
int res;
vector<vector<int>> map1;
vector<vector<int>> map2;
int dp[10][1025];
int maxStudents(vector<vector<char>>& seats) {
n = seats.size();
m = seats[0].size();
for(int i=0;i<n;i++)
{
vector<int> x;
vector<int> y;
fun(seats,i,0,x,y,0,0);
map1.push_back(x);
map2.push_back(y);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<map1[i].size();j++)
{
if(i==0)
dp[i][map1[i][j]]=map2[i][j];
else
{
for(int k=0;k<map1[i-1].size();k++)
{
if(((map1[i][j]<<1) & map1[i-1][k])||((map1[i][j]>>1) & map1[i-1][k]))
{
continue;
}
dp[i][map1[i][j]]=max(dp[i][map1[i][j]],dp[i-1][map1[i-1][k]]+map2[i][j]);
}
}
}
}
for(int i=0;i<map1[n-1].size();i++)
{
res=max(res,dp[n-1][map1[n-1][i]]);
}
return res;
}
void fun(vector<vector<char>>& seats,int pos,int tag,vector<int>& s1,vector<int>& s2,int seat1,int seat2)
{
if(tag==seats[pos].size())
{
s1.push_back(seat1);
s2.push_back(seat2);
return;
}
seat1 <<= 1;
if(seats[pos][tag]=='.')
{
if(tag==0||seats[pos][tag-1]!='.')
{
fun(seats,pos,tag+1,s1,s2,seat1+1,seat2+1);
}
}
char c = seats[pos][tag];
seats[pos][tag]='#';
fun(seats,pos,tag+1,s1,s2,seat1,seat2);
seats[pos][tag]=c;
}
};
以上是关于1349. Maximum Students Taking Exam(DP,状态压缩)的主要内容,如果未能解决你的问题,请参考以下文章
CreateProcessWithUser 无法模拟用户,出现错误 87、1349
1349: Taking Pebbles (博弈 打表找规律)