跳到正文

题解

题解:CF1834F Typewriter

GavinCQTD约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年4月14日
收录
2026年4月14日
更新
2026年11月15日
篇幅
约 5 分钟
题目
CF1834F

版本

  1. v1当前

挺牛的一道题。

我们先考虑单次答案求的到底是什么。根据题意,往右移动是无代价的,而往左移则需要 11 的代价。

那单次答案就是需要往左移动的元素个数。

Ans=∑i=1n[pi<i]Ans = \sum_{i=1}^{n} [p_{i} < i]

接下来我们引入移动与翻转操作。有个很妙的点是,加上这两种操作,排列也只有 2×n2 \times n 种情况,我们完全可以预处理出来,后面维护一个偏移量和一个翻转标志,最后只需 O(1)O(1) 查询答案。下述偏移量均为向右移动时的偏移量。

先来看没翻转的情况。显然,我们只需要算出一个元素对答案的哪些区间有所贡献。

设 vv 表示当前元素 pip_{i},我们希望它对答案有贡献,即要求它的值小于它的新位置。

v<new_pos  ⟹  new_pos∈[v+1,n]v < new\_pos \implies new\_pos \in [v + 1, n]

这样的有效位置有 n−(v+1)+1n-(v+1)+1 也就是 n−vn-v 个。

贡献开始的偏移量就是 vv 这个元素移到 v+1v+1 这个位置需要的步数,注意考虑循环。

S=(v+1−i+n)(modn)S = (v + 1 - i + n) \pmod n

这一块不用写树状数组什么的,维护答案数组的差分数组,每次直接在端点加减即可,最后做前缀和。注意判一下,如果贡献区间的右端点 r≥nr \ge n 了,那需要把溢出的一部分放到左边去。

翻转过来也是一样的。

对于移动操作,算新的偏移量就可以。注意第三个操作,更新翻转标志以后,偏移量也是随之变化了的,具体的式子写在下面了。

offset=(n−offset)(modn)offset = (n - offset) \pmod n

代码是很短的,复杂度线性。

C++
/******************************
 - @GavinCQTD / 2026-04-14 08:03:34
 - "F. Typewriter" From Codeforces - Codeforces Round 879 (Div. 2)
 - # https://codeforces.com/problemset/problem/1834/F
 - 3000 ms / 256 MB
******************************/

#include <algorithm>
#include <iostream>
#include <cassert>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;

int n,q,p[2][400005],ans[2][400005];

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    cin >> n;
    for(int i=1;i<=n;i++){
        cin >> p[0][i];
        p[1][i] = p[0][i];
    }

    reverse(p[1]+1,p[1]+n+1);

    for(int i=1;i<=n;i++){
        for(int _=0;_<=1;_++){
            int L=n-p[_][i],l=(p[_][i]+1-i+n)%n,r=l+L-1;
            if(L==0){
                continue;
            }

            if(r<n){
                ans[_][l]++;
                ans[_][r+1]--;
            }
            else{
                ans[_][l]++;
                ans[_][n]--;
                ans[_][0]++;
                ans[_][r-n+1]--;
            }
        }
    }

    for(int i=1;i<=n;i++){
        ans[0][i] += ans[0][i-1];
        ans[1][i] += ans[1][i-1];
    }

    int rev=0,off=0;
    cin >> q;
    cout << ans[rev][off] << "\n";
    for(int i=1;i<=q;i++){
        int op;
        cin >> op;

        if(op==1){
            int k;
            cin >> k;
            off = ((off-k)%n+n)%n;
        }

        else if(op==2){
            int k;
            cin >> k;
            off = (off+k)%n;
        }

        else{
            rev ^= 1;
            off = (n-off)%n;
        }

        cout << ans[rev][off] << "\n";
    }

    return 0;
}
原文
存档评论3 条抓取于