1293: [SCOI2009]生日礼物
Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 3183 Solved: 1767
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。
解析:
单调队列。两种写法。
一种是将彩珠按位置排序二分答案+单调队列。
一种是用尺取法。具体来说设一个头指针和一个尾指针,尾指针先往右移至刚好满足条件的位置(继续往后移一定没有现在优),左指针往右移至刚好不满足条件并在移动过程中记录答案。重读上述操作可得到最优解。
代码(二分):
#include <bits/stdc++.h>
using namespace std;
const int Max=1000010;
int n,m,k,tot,cnt[65],sum,p[Max];
struct shu{int pos,id;}num[Max];
inline int get_int()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') f=-1,c=getchar();
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline bool comp(const shu &a,const shu &b){return a.pos<b.pos;}
inline bool check(int mid)
{
int head=1,tail=0;sum=0;
for(int i=1;i<=k;i++) cnt[i]=0;
for(int i=1;i<=n;i++)
{
int color;
while(head<=tail&&num[head].pos<num[i].pos-mid)
{
color=num[p[head++]].id;
cnt[color]--;
if(!cnt[color]) sum--;
}
p[++tail]=i,color=num[i].id,cnt[color]++;
if(cnt[color]==1) sum++;
if(sum==k) return 1;
}
return 0;
}
inline void solve()
{
int l=0,r=num[n].pos-num[1].pos+1,mid;
while(l<r)
{
mid=(l+r)>>1;
if(check(mid)) r=mid;
else l=mid+1;
}
cout<<r;
}
int main()
{
n=get_int(),k=get_int();
for(int i=1;i<=k;i++)
{
m=get_int();
while(m--)num[++tot].id=i,num[tot].pos=get_int();
}
sort(num+1,num+tot+1,comp);
solve();
return 0;
}
代码(尺取法)来自:2018.10.10 bzoj1293: [SCOI2009]生日礼物(双指针)
#include<bits/stdc++.h>
#define N 1000005
using namespace std;
inline int read(){
int ans=0;
char ch=getchar();
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
return ans;
}
int n,k,ans=2e9,tot=0,cnt[70],colors=0;
struct Node{int col,pos;}p[N];
inline bool cmp(Node a,Node b){return a.pos<b.pos;}
int main(){
n=read(),k=read();
for(int i=1;i<=k;++i){
int t=read();
while(t--)p[++tot]=(Node){i,read()};
}
sort(p+1,p+n+1,cmp);
for(int l=1,r=0;l<=n;){
while(colors<k&&r<n){
++r,++cnt[p[r].col];
if(cnt[p[r].col]==1)++colors;
}
while(colors>=k){
ans=min(ans,p[r].pos-p[l].pos);
--cnt[p[l].col];
if(!cnt[p[l].col])--colors;
++l;
}
if(r==n)break;
}
cout<<ans;
return 0;
}