[AT1832 回転寿司]题解
brokenblade · · 题解
崩溃历程:
看到时间限制将近
(这不是
看到这神奇的区间操作,我的心情是疑惑的。
想到每次只要找出最大的然后大根堆维护一下的时候,我的心情是生草的。
打完代码然后尝试调的时候被大数据卡到
最后偷偷开
解法介绍:
这道题目很明显的是他的操作是将从
由此可以看出,最后弹出的永远都是这一区间的最大值。
这时候我们尝试构造数据。
如果我们有一种特殊数据使得
由这组特性,我们可以想到优雅地暴力:分块。
我们可以考虑 分块+堆 来优雅地解决问题。。。
考虑块与块之间的处理,也就是整块的时候。
显然,整块的时候影响块内元素的只有插入的值和被弹出的最大值,而被弹出的最大值继承到下一个块内,以此类推,就可以完成块的处理与合并。
但块内暴力该如何处理呢?(散块该如何处理)
考虑如何重构,我们可以考虑到任何一盘寿司能够插进,与它插进的顺序没有任何的关系。也就是说: 插入值的顺序与最后的值没有任何关系。
所以我们考虑暴力重构时,我们只要考虑插入的值就可以了。
显然的是,当前位置的更新肯定是当前位置最小的。
于是就自然得想到了小根堆动态维护暴力重构,从小到大维护原始序列(原始块),再压入大根堆中。
因为一位顾客的寿司可能会影响到后面顾客的寿司,所以我们可以把顾客的寿司看做转过来的寿司,也把他放到小根堆中。
由于注意到题目拥有良好的对称性,我们既可以理解为寿司依次经过顾客,我们也可以理解为顾客经过了寿司。
(所以你可以近似的认为顾客把顾客吃了
时间复杂度分析
我们对于整块操作,额外记下了插入的值,记录下来的寿司当做顾客,顾客当做寿司来执行操作,并用小根堆维护。每一操作的时间复杂度为
我们取块长
代码部分
#include<bits/stdc++.h>
#define Debug if(false)
#define rnt register int
using namespace std;
const int maxn=400010,maxb=670;
inline int read()
{
int x=0,f=1;char c;
for(;!isdigit(c);c=getchar()) if(c=='-') f=-f;
for(;isdigit(c);c=getchar()) x=(x<<1)+(x<<3)+(c^48);
return x*f;
}
int n,m,bs,mb,block[maxn],a[maxn];
inline int get(int x){return x+1>mb?1:x+1;} //循环
struct Block
{
int l,r;
priority_queue<int,vector<int>,less<int> > que;
priority_queue<int,vector<int>,greater<int> > tag; //只需要记录值
inline int modify(int x) //块修改,从左往右扫这个块并把最大值弹出,人称暴力修改
{
if(x>=que.top()) return x; //无法过去了
int res=que.top();que.pop();
que.push(x),tag.push(x);
return res; //把最大的pop出去
}
inline void rebuild() //重构,按最小取
{
if(!tag.size()) return;
for(rnt i=l;i<=r;i++)
if(tag.top()<a[i])
{
int tis=a[i];
a[i]=tag.top(),tag.pop();
tag.push(tis);
}
}
inline void clear()
{
while(!tag.empty()) tag.pop();
while(!que.empty()) que.pop();
}
inline int query(int x,int L,int R) //暴力重置
{
rebuild(),clear();
for(rnt i=L;i<=R;i++) if(a[i]>x) swap(a[i],x);
for(rnt i=l;i<=r;i++) que.push(a[i]);
return x;
}
}b[maxb];
inline void init_block() //基本操作
{
n=read(),m=read();
bs=sqrt(n),mb=((n-1)/bs)+1;
for(rnt i=1;i<=n;i++)
{
a[i]=read();
block[i]=(i-1)/bs+1;
b[block[i]].que.push(a[i]);
}
for(rnt i=1;i<=mb;i++)
b[i].l=bs*(i-1)+1,b[i].r=bs*i;
b[mb].r=n;
}
signed main()
{
// freopen("D.in","r",stdin);
// freopen("D.out","w",stdout);
init_block();
while(m--)
{
int s=read(),t=read(),p=read();
Debug printf("block[%d]: %d block[%d]: %d\n",s,block[s],t,block[t]);
if(block[s]==block[t]&&s<=t) //同一块中可以直接查询
printf("%d\n",b[block[s]].query(p,s,t));
else //跳块,基本操作。
{
p=b[block[s]].query(p,s,b[block[s]].r);
int cur=get(block[s]);
while(cur!=block[t])
p=b[cur].modify(p),cur=get(cur);
Debug cout << cur << endl;
printf("%d\n",b[block[t]].query(p,b[block[t]].l,t));
}
}
return 0;
}