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

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1293

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

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

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

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

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

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

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

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std; const int maxn=1e6+5; int sum[65],list[maxn];
int n,head,tail,ans=1e9,cnt,id; 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(),cnt=read();
for(int i=1;i<=cnt;i++) {
int tot=read();
for(int j=1;j<=tot;j++)
c[++id].pos=read(),c[id].id=i;
}
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;
}

最新文章

  1. 第 29 章 CSS3 弹性伸缩布局[上]
  2. 【转载】Myeclipse如何自动创建hibernate
  3. Super关键字
  4. delphi 7 下安装 indy 10.5.8 教程
  5. eclipse加入辅助线,配合代码格式化使用
  6. Quartz.net 定时计划使用
  7. PHP常用表达式用法
  8. Uva 10550 Combination Lock
  9. directdraw显示rgb555
  10. DOM相关知识
  11. 基于ASP.NET MVC 微信网页登录授权(scope为snsapi_base) 流程 上 获取OPENID
  12. Codeforces 1090M - The Pleasant Walk - [签到水题][2018-2019 Russia Open High School Programming Contest Problem M]
  13. jsp操作MySQL时报错:Operation not allowed after ResultSet closed
  14. UVALive 5846 计数
  15. 一、BOM 二、DOM
  16. TPO-20-Apply for the undergraduate research fund
  17. ASP.NET中的几种弹出框提示基本实现方法
  18. docker 存储驱动之 overlay2
  19. xp,win7,win10系统安装GHO镜像下载
  20. LeetCode 417. Pacific Atlantic Water Flow

热门文章

  1. 自己动手编译Android源码(超详细)
  2. Django---view视图FBV&amp;CBV
  3. 20145230《java学习笔记》第十周学习总结
  4. 如何用hexo+github搭建个人博客
  5. 用代码实现断开Android手机USB连接【转】
  6. RDLC 微软报表 自定义函数
  7. Linux挂载第二块硬盘操作方法
  8. PBKDF2加密
  9. Maven——安装配置
  10. UVA 11029 || Lightoj 1282 Leading and Trailing 数学