单调栈-LeetCode 85.最大矩形
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
枚举每一行,当前行的每一列就可以组成一个类似于上图的柱状图,然后就是求柱状图中的最大矩形,更新最大值即可.
stack<int> s;
vector<int> v;
class Solution
{
public:
int maximalRectangle(vector<vector<char>>& matrix)
{
if(matrix.empty()) return 0;
int row=matrix.size(),col=matrix[0].size();
v.clear();
int ans=0;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
if(i==0)
{
v.push_back(matrix[i][j]=='1'?1:0);
}
else
{
v[j]=(matrix[i][j]=='1'?v[j]+1:0);
}
}
ans=max(ans,largestRectangleArea());
}
return ans;
}
int largestRectangleArea()
{
while(!s.empty()) s.pop();
int maxarea=0,n=v.size();
s.push(-1);
for(int i=0; i<n; i++)
{
while(s.top()!=-1&&v[s.top()]>=v[i])
{
int top=s.top();
s.pop();
maxarea=max(maxarea,v[top]*(i-s.top()-1));
}
s.push(i);
}
while(s.top()!=-1)
{
int top=s.top();
s.pop();
maxarea=max(maxarea,v[top]*(n-s.top()-1));
}
return maxarea;
}
};
优先队列-AtCoder Beginner Contest 137 D - Summer Vacation
Problem Statement
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of Bi after Ai days from the day you do it.
You can take and complete at most one of these jobs in a day.
However, you cannot retake a job that you have already done.
Find the maximum total reward that you can earn no later than M days from today.
You can already start working today.
Constraints
- All values in input are integers.
- 1≤N≤10^5
- 1≤M≤10^5
- 1≤Ai≤10^5
- 1≤Bi≤10^4
Input
Input is given from Standard Input in the following format:
N M
A1 B1
A2 B2
⋮
AN BN
Output
Print the maximum total reward that you can earn no later than M days from today.
Sample Input 1
3 4
4 3
4 1
2 2
Sample Output 1
5
当B[i]=B[j],优先选择min(A[i],A[j]),因此从后往前枚举m天,即可用天数必须是从小到大的,然后借助于优先队列的特殊性质.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
vector<int>v[maxn];
priority_queue<int>q;
int main()
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
for(int i=0;i<n;i++){
scanf("%d%d",&a,&b);
v[a].push_back(b);
}
int ans=0;
for(int i=1;i<=m;i++){
for(auto c:v[i]) q.push(c);
if(!q.empty()){
ans+=q.top();
q.pop();
}
}
printf("%d\n",ans);
}