版权声明:欢迎转载(标记出处),写得不好还请多指教 https://blog.csdn.net/quan_tum/article/details/82764384
传送门
把珠子按位置排序
当
时,
为
,那么
入队,
更新
的值为
当队头
且队头的元素所在位置
不等于该位置珠子最后出现的位置时出队。
当
=
时更新答案
从头枚举到尾就好了,时间复杂度
,其实还有
的做法。
#include<bits/stdc++.h>
#define il inline
using namespace std;
const int N=1e6+5;
#define getchar()(p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char buf[1<<21],*p1=buf,*p2=buf;
il int read(){
int x=0,f=1;char c=getchar();
for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
for(;isdigit(c);c=getchar()) x=(x+(x<<2)<<1)+c-48;
return x*f;
}
struct A{int c,p;}a[N];
int n,k,ans,pos[N],m,h=1,ct;
il bool cmp(A x,A y){return x.p<y.p;}
int main(){
n=read(),k=read();
for(int i=1,x;i<=k;++i){
x=read();pos[i]+=x;
for(int j=1;j<=x;++j) a[++m].p=read(),a[m].c=i;
}
sort(a+1,a+n+1,cmp);
ans=a[n].p-a[1].p;
memset(pos,-1,sizeof(pos));
for(int i=1;i<=n;++i){
if(pos[a[i].c]==-1) ++ct;
pos[a[i].c]=a[i].p;
while(h<=i&&a[h].p!=pos[a[h].c]) ++h;
if(ct==k&&a[i].p-a[h].p<ans) ans=a[i].p-a[h].p;
}
return !printf("%d",ans);
}