这个题的翻译是“挤奶牛”,我估计只有机器翻译才能给出这么强的翻译了。
好了,闲话不多说。这个题是我用来学算法的。单调队列。
先来一段代码。
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
struct qnode{
int lo;int h;int num;
};
qnode q[100000+666];
qnode a[500000+666];
bool yes[500000+666];
bool yes2[500000+666];
int n,d;
int hh,tt;
inline int ra()
{
int x=0;char ch=getchar();int flag=1;
while(ch>'9'||ch<'0'){if(ch=='-')flag=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x*=10;x+=ch-'0';ch=getchar();}
return x*flag;
}
bool cmp(const qnode a,const qnode b)
{
return a.lo<b.lo;
}
void in(qnode now)
{
while(q[hh-1].h<now.h&&hh!=tt)hh--;//别把队列清空
q[hh++]=now;
while(abs(now.lo-q[tt].lo)>d)tt++;
return;
}
void check()
{
if(q[tt].h>=2*q[hh-1].h)
{
yes[q[hh-1].num]=1;
}
return;
}
void check2()
{
if(q[tt].h>=2*q[hh-1].h)
{
yes2[q[hh-1].num]=1;
}
}
int main()
{
n=ra();d=ra();
for(int i=1;i<=n;i++)
{
a[i].lo=ra();a[i].h=ra();a[i].num=i;
}
sort(a+1,a+n+1,cmp);
hh=tt=0;
for(int i=1;i<=n;i++)
{
in(a[i]);
check();
}
hh=tt=0;
memset(q,0,sizeof(q));
for(int i=n;i>=1;i--)
{
in(a[i]);
check2();
}
int ans=0;
for(int i=1;i<=n;i++)if(yes[i]&&yes2[i])++ans;
printf("%d",ans);
/*cout<<endl;*/
/* printf("\n");
for(int i=1;i<=n;i++)cout<<yes[i]<<' ';
cout<<endl;
for(int i=1;i<=n;i++)cout<<yes2[i]<<' ';
cout<<endl;*/
return 0;
}
从前做过一个叫“烽火台”的题,是ly的模拟赛,那个时候就听过单调队列这种东西,当时是用来优化DP的,但是不知道当时自己是怎么了,反正没学,到现在才想起来。
于是做了一道题。
这个题本来是可以用set加循环NlogN搞定的,但是毕竟是来学算法的。
用单调性来维护队列,但是要注意的一点是,不要把队列清空(因为队列的初始值是0,所以单纯判断大小是不行的)。
其实单调队列就是在入队的时候要维护单调性,其他的没有什么难点。
但是单调队列的题常常带着时效性,这时候就需要开一个结构体,在入队维护单调性的同时维护时效性(本体的距离就是时效性)。
单调队列是O(n)的,可以说很优了。