当前位置: 代码迷 >> 综合 >> BZOJ1293 [SCOI2009]生日礼物
  详细解决方案

BZOJ1293 [SCOI2009]生日礼物

热度:75   发布时间:2023-12-14 17:03:41.0

标签:单调队列

Description

小西有一条很长的彩带,彩带上挂着各式各样的彩珠。已知彩珠有N个,分为K种。简单的说,可以将彩带考虑为x轴,每一个彩珠有一个对应的坐标(即位置)。某些坐标上可以没有彩珠,但多个彩珠也可以出现在同一个位置上。 小布生日快到了,于是小西打算剪一段彩带送给小布。为了让礼物彩带足够漂亮,小西希望这一段彩带中能包含所有种类的彩珠。同时,为了方便,小西希望这段彩带尽可能短,你能帮助小西计算这个最短的长度么?彩带的长度即为彩带开始位置到结束位置的位置差。

Input

第一行包含两个整数N, K,分别表示彩珠的总数以及种类数。接下来K行,每行第一个数为Ti,表示第i种彩珠的数目。接下来按升序给出Ti个非负整数,为这Ti个彩珠分别出现的位置。

Output

应包含一行,为最短彩带长度。

Sample Input

6 3

1 5

2 1 7

3 1 3 8

Sample Output

3

HINT

有多种方案可选,其中比较短的是1~5和5~8。后者长度为3最短。
【数据规模】
对于50%的数据, N≤10000;
对于80%的数据, N≤800000;
对于100%的数据,1≤N≤1000000,1≤K≤60,0≤彩珠位置<2^31。

 

分析:

用num数组记录每个彩珠出现的位置和种类,然后按照位置从小到大排序,从头到尾扫一遍,类似于队列的做法

注意:这题一定要把inf置为0x7fffffff,用0x3f3f3f会WA

Code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#ifdef WIN32
#define LL "%I64d"
#else
#define LL "%lld"
#endif 
using namespace std;
inline ll read()
{ll f=1,x=0;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;
}
const int maxn=1000006;
int inque[maxn],flag=0,ans=0x7fffffff,n,k,x,cnt=0,head,tail;
struct node{int pos,type;}num[maxn],que[maxn<<1];
inline bool cmp(node a,node b){return a.pos==b.pos?a.type<b.type:a.pos<b.pos;}
void check()
{rep(j,1,k)if(!inque[j])return;flag=1;
}
int main()
{n=read(),k=read();rep(i,1,k){x=read();rep(j,1,x)num[++cnt].pos=read(),num[cnt].type=i; }sort(num+1,num+1+n,cmp);//rep(i,1,n)cout<<num[i].pos<<' '<<num[i].type<<endl; head=tail=1;que[head]=num[1];inque[que[head].type]=que[head].pos;while(head<=tail&&tail<n){que[++tail]=num[tail];inque[que[tail].type]=que[tail].pos;while(inque[que[head].type]>que[head].pos)head++;if(!flag)check();if(flag)ans=min(ans,que[tail].pos-que[head].pos);//cout<<head<<' '<<tail<<' '<<flag<<endl;//rep(j,1,k)cout<<inque[j]<<}cout<<ans<<endl;return 0;
}