1 条题解

  • 0
    @ 2026-3-5 9:27:47

    文字教学

    这道题用三个前缀和数组分别统计三个品种的数量,实现高效查询:

    1. 定义 s1[i]s2[i]s3[i] 分别表示前 i 头奶牛中品种1、2、3的数量。
    2. 预处理:遍历每头奶牛,对应品种的前缀和数组在当前位置加1,其余品种继承前一个位置的值。
    3. 查询区间 [a,b] 时,每个品种的数量 = 该品种前缀和在 b 位置的值 - 在 a-1 位置的值。

    代码

    #include <bits/stdc++.h>
    using namespace std;
    
    int s1[100005], s2[100005], s3[100005];
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(0);
        int n, q, x, a, b;
        cin >> n >> q;
        for (int i = 1; i <= n; ++i) {
            cin >> x;
            s1[i] = s1[i-1];
            s2[i] = s2[i-1];
            s3[i] = s3[i-1];
            if (x == 1) s1[i]++;
            else if (x == 2) s2[i]++;
            else s3[i]++;
        }
        while (q--) {
            cin >> a >> b;
            cout << s1[b]-s1[a-1] << " " << s2[b]-s2[a-1] << " " << s3[b]-s3[a-1] << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    5159
    时间
    2000ms
    内存
    250MiB
    难度
    3
    标签
    递交数
    8
    已通过
    6
    上传者