跳到正文

个人记录

洛谷 - P3939

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

文章信息

发布
2025年8月9日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前

题意

给定一个长度为 nn 的序列 a1,a2,…,ana_1,a_2,\dots,a_n。

mm 次操作:

  • 1 l r c 查询区间 [l,r][l,r] 中有多少个值为 cc 的数。
  • 2 x 交换 axa_x 和 ax+1a_{x + 1}

思路

用 map 套 vector 维护所有颜色的所有位置,按从小到大的顺序排列。

  • 第一种操作二分找到 ll 和 rr 的位置,两个位置相减可得到个数。
  • 第二种操作可以将交换两个位置的颜色变为交换两个颜色的位置,在 map 套 vector 里交换。

代码

C++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;

const ll N = 3e5 + 2;
ll n, m;
ll a[N];
ll op, l, r, c, x;

vector <ll> v[N];

ll p1, p2;

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

///    freopen("P3939_4.in", "r", stdin);
///    freopen("P3939.out", "w", stdout);

    cin >> n >> m;
    for(ll i = 1; i <= n; i ++){
        cin >> a[i];
        v[a[i]].push_back(i);
    }

    while(m --){
        cin >> op;
        if(op == 1){
            cin >> l >> r >> c;

            p1 = lower_bound(v[c].begin(), v[c].end(), l) - v[c].begin();
            p2 = upper_bound(v[c].begin(), v[c].end(), r) - v[c].begin();

            cout << p2 - p1 << '\n';
        }
        else{
            cin >> x;

            if(a[x] == a[x + 1]){
                continue;
            }

            p1 = lower_bound(v[a[x]].begin(), v[a[x]].end(), x) - v[a[x]].begin();
            p2 = lower_bound(v[a[x + 1]].begin(), v[a[x + 1]].end(), x + 1) - v[a[x + 1]].begin();

            v[a[x]][p1] ++;
            v[a[x + 1]][p2] --;

            swap(a[x], a[x + 1]);
        }
    }

    return 0;
}

原文