题解 P3029 【[USACO11NOV]牛的阵容Cow Lineup】

· · 题解

update 2020/1/18,修改了一些小细节

双倍经验:P2564 [SCOI2009]生日礼物

不需要STL队列!不需要手写队列!不需要双端队列!直接用双指针!

首先,将所有牛按照坐标升序排列,并把他们那又臭又长的ID利用 map 换成一个连续的ID
数组 c[] 维护当前区间 [l,r] 中每种牛出现的次数,sum 记录当前区间内牛的种类总数,tot 为总共牛的种数,最开始 l=1,r=0

接下来开始枚举:

若当前区间sum<tot,说明牛的种数还不够,就把区间往右扩展 ++r 并维护 c[id[r]],sum
然后,将区间最左边的多余的牛弹掉。也就是如果 c[id[l]]>1 ++l注意: 如果弹掉了牛一定要更新c[]sum

最后,如果还是 sum<tot,重复上面操作。如果 sum=tot 就更新答案并且++l

代码:

#include<cstdio>
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
const int Maxn=50000+20,inf=0x3f3f3f3f;
map <int , int> vis;
int a[Maxn],id[Maxn],c[Maxn];
struct cow{
    int x,d;
}srt[Maxn];
int n,ans=inf,tot;
inline bool cmp(cow u,cow v)
{
    return u.x<v.x;
}
inline int read()
{
    int s=0,w=1;
    char ch=getchar();
    while(ch<'0' || ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
    return s*w;
}
int calc(int x)
{
    if(!vis[x])vis[x]=++tot;
    return vis[x];
}
int main()
{
//  freopen("in.txt","r",stdin);
    n=read();
    for(int i=1;i<=n;++i)
    {
        srt[i].x=read();
        int tmp=read();
        srt[i].d=calc(tmp);
    }
    sort(srt+1,srt+1+n,cmp); //结构体仅用来排序
    for(int i=1;i<=n;++i)
    a[i]=srt[i].x,id[i]=srt[i].d;

    int l=1,r=0,sum=0;
    while(r<n)
    {
        ++r,c[id[r]]++; //记得统计c[]和sum!
        if(c[id[r]]==1)++sum;
        while(c[id[l]]>1)
        {
            c[id[l]]--;
            if(!c[id[l]])--sum;
            ++l;
            if(l>r)break; //如果区间里已经没东西了就 break
        }
        if(sum==tot)
        {
            ans=min(ans,a[r]-a[l]); //更新答案
            c[id[l]]--; //记得统计c[]和sum!
            if(!c[id[l]])--sum;
            ++l;
        }
    }

    printf("%d\n",ans);

    return 0;
}