Input
第1行:2个数N, M中间用空格分隔,N为井的深度,M为盘子的数量(1 <= N, M <= 50000)。
第2 - N + 1行,每行1个数,对应井的宽度Wi(1 <= Wi <= 10^9)。
第N + 2 - N + M + 1行,每行1个数,对应盘子的宽度Di(1 <= Di <= 10^9)
Output
输出最终落到井内的盘子数量。
Input示例
7 5
5
6
4
3
6
2
3
2
3
5
2
4
Output示例
4
地址:http://www.51nod.com/Challenge/Problem.html#problemId=1279
思路:对于盘子落在什么位置,需要从井口一直向下来判断,那么对于井来说,若上一层 a[i-1] 比下一层 a[i] 窄,那么就会卡在上一层,因此下一层的宽度可等价于上一层的高度即 a[i]=a[i-1],对所有a[i]预处理后,就可以直接从井的底部开始判断了
Code:
#include<iostream>
using namespace std;
const int MAX_N=5e4+5;
int n,m;
int a[MAX_N];
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
a[0]=1e9+1;
for(int i=1;i<=n;++i)
{
cin>>a[i];
a[i]=min(a[i-1],a[i]);
}
int res=0,l=n,x;
for(int i=0;i<m;++i)
{
cin>>x;
while(l>0&&a[l]<x){
--l;
}
if(l>0){
++res; --l;
}
}
cout<<res<<endl;
return 0;
}
思路: 对于盘子落在什么位置,需要从井口一直向下来判断,当本题数据过大,若每个盘子都这样判断则会超时,因此我们需要优化,可预先求出每个盘子会下落的位置 h[i],先对盘子由大到小排序,先求出大的盘子下落的位置 t ,再求小的盘子时,则不用再考虑 t 以上的位置了,因此可快速求出所有盘子的下落位置。 在按照盘子下落的顺序,设置一个盘子能到达的最低的位置down, 最初down=n-1,(井由 0->n-1) 由盘子的下落位置 h[i]位于 down下面,则更新 down+1,ans++;若在h 上面,则 down=h[i]-1, ans++; 若 h[i] 或 down 都 小于 0 ,即都不在井内,则结束循环。
code:
#include<iostream>
#include<queue>
using namespace std;
const int MAX_N=50005;
const int MAX_M=50005;
struct node{
int x;
int id;
bool operator<(const node&a)const{
return x<a.x;
}
};
int n,m,ans;
int a[MAX_N];
int b[MAX_M],h[MAX_M];
priority_queue<node> Q;
int main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
for(int i=0;i<n;++i)
cin>>a[i];
for(int i=0;i<m;++i)
{
cin>>b[i];
Q.push(node{b[i],i});
}
int t=0;
while(!Q.empty()){
int x=Q.top().x;
while(x<=a[t]&&t<n){
t++;
}
h[Q.top().id]=t-1;
Q.pop();
}
int down=n-1;
for(int i=0;i<m;++i)
{
if(h[i]<0||down<0) break;
if(h[i]>=down) down--;
else down=h[i]-1;
ans++;
}
cout<<ans<<endl;
return 0;
}