[ABC389C] Snake Queue 题解
前置知识
- 手写队列
- 前缀和
题目大意
有一个队列,起初为空,有 $Q$ 次询问,要能进行加入,删除,查询第 $k$ 个元素三种操作。
思路
暴力
直接使用 STL 中的 queue。对于加入和删除,可以做到 $O(1)$ 的时间复杂度;对于查询,先将前 $k-1$ 个元素弹出,再输出答案,最后将元素重新加入队列,设 $n$ 为当前队列的长度,则时间复杂度为 $O(n^2)$。
正解
发现查询操作过于复杂,所以可以手写队列,这样就可以通过下标进行 $O(1)$ 查询,再加以前缀和维护。
细节
- 空间需要开到 $2 \times Q$
- 记得开 long long!
代码参考
// Problem: C - Snake Queue
// Contest: AtCoder - Toyota Programming Contest 2025(AtCoder Beginner Contest 389)
// URL: https://atcoder.jp/contests/abc389/tasks/abc389_c
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=6e5+10;//两倍空间
int q;
ll a[N],cnt,tot;
int main(){
scanf("%d",&q);
while(q--){
int op,x;
scanf("%d",&op);
if(op==1){
scanf("%d",&x);
++cnt;
a[cnt+1]=a[cnt]+x;//这条蛇的长度应该贡献给下一条蛇
}
if(op==2){
++tot;
}
if(op==3){
scanf("%d",&x);
int tmp=tot+x;
printf("%lld\n",a[tmp]-a[tot+1]);
}
}
return 0;
}

浙公网安备 33010602011771号