跳到正文

题解

题解:AT_abc425_c [ABC425C] Rotate and Sum Query

New_Void约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年10月28日
篇幅
约 3 分钟

版本

  1. v1当前

AT_abc425_c [ABC425C] Rotate and Sum Query

十分简单的一道题。

思路

这道题十分经典,是个练习的好题。

首先直接模拟移动操作会超时,因为每次移动需要 O(N)O(N) 的时间,而 NN 和 QQ 都可能达到 2×1052 \times 10^5。

那么我们要怎么办呢?很显然我们可以维护个指针 cntcnt 来表示当前序列的起始位置在原数组中的下标。

之后我们根据这个指针,来确定新的左端点和右端点,然后进行区间求和,可以用前缀和或树状数组或线段树来实现以及其他算法,本作者作为一个树状数组爱好者,所以用树状数组进行了区间求和,这样这道题就完美的写完了。

Code

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=2e5+5;
int tree[N];
int a[N];
int n,q;
void add(int x,int k){
    for (;x<=n;x+=x&-x) tree[x]+=k;
}
int sum(int x){
    int res=0;
    for (;x;x-=x&-x) res+=tree[x];
    return res;
}
int query(int l,int r){
    return sum(r)-sum(l-1);
}
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin>>n>>q;
    for (int i=1;i<=n;i++){
        cin>>a[i];
        add(i,a[i]);
    }
    int cnt=0;
    while (q--){
        int opt;cin>>opt;
        if (opt==1){
            int c;cin>>c;
            cnt=(cnt+c)%n;
        }
        else{
            int l,r;cin>>l>>r;
            int L=(cnt+l-1)%n+1;
            int R=(cnt+r-1)%n+1;
            int ans=0;
            if (L<=R) cout<<query(L,R)<<endl;
            else cout<<query(L,n)+query(1LL,R)<<endl;
        }
    }
    return 0;
}
原文