洛谷【P3029】[USACO11NOV]Cow Lineup

浅谈队列:https://www.cnblogs.com/AKMer/p/10314965.html

题目传送门:https://www.luogu.org/problemnew/show/P3029

这里介绍一种尺取法。(此处的尺意味游标卡尺)

从左至右依次测量以当前点为右端点的区间“长度”,那么左端点呢?

能用尺取法做的题必然满足当右端点不断往右移的时候,左端点不会往左移。

所以我们每次就去\(check\)一下左端点是否能往右移,如果可以那就不断地去“卡紧”测量范围。

对于这个题,用队列表示卡尺范围,我们可以开一个全局的桶,存每个品种的牛在卡尺范围内有多少头。如果左端点的牛品种不止一头那么肯定可以把左端点往右边靠的。然后每次更新最小值即可。

时间复杂度:\(O(n)\)

空间复杂度:\(O(n)\)

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn=5e4+5;

int n,head,tail,ans=1e9,cnt;
int sum[maxn],list[maxn],tmp[maxn];

int read() {
    int x=0,f=1;char ch=getchar();
    for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
    for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
    return x*f;
}

struct cow {
    int pos,id;

    bool operator<(const cow &a)const {
        return pos<a.pos;
    }
}c[maxn];

int main() {
    n=read();
    for(int i=1;i<=n;i++)
        c[i].pos=read(),tmp[i]=c[i].id=read();
    sort(tmp+1,tmp+n+1);
    cnt=unique(tmp+1,tmp+n+1)-tmp-1;
    for(int i=1;i<=n;i++)
        c[i].id=lower_bound(tmp+1,tmp+cnt+1,c[i].id)-tmp;
    sort(c+1,c+n+1);
    for(int i=1;i<=n;i++) {
        int id=c[i].id;
        if(!sum[id])cnt--;
        sum[id]++;list[tail++]=i;
        while(sum[c[list[head]].id]>1)sum[c[list[head]].id]--,head++;
        if(!cnt)ans=min(ans,c[list[tail-1]].pos-c[list[head]].pos);
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/AKMer/p/10323600.html
今日推荐