1 条题解

  • 0
    @ 2026-11-2 15:26:16

    区间统计问题(Subarray Range Count) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <vector>
    #include <string>
    #include <algorithm>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        if (!(cin >> n)) return 0;
        vector<long long> a(n), b(n);
        for (int i = 0; i < n; ++i) cin >> a[i];
        for (int i = 0; i < n; ++i) cin >> b[i];
        vector<pair<long long, long long>> stk;
        stk.reserve(n);
        long long curS = 0;
        __int128 ans = 0;
        for (int i = 0; i < n; ++i) {
            long long cnt = 1;
            while (!stk.empty() && stk.back().first <= a[i]) {
                curS -= stk.back().first * stk.back().second;
                cnt += stk.back().second;
                stk.pop_back();
            }
            stk.push_back({a[i], cnt});
            curS += a[i] * cnt;
            ans += (__int128)curS * b[i];
        }
        if (ans == 0) {
            cout << 0 << "\n";
            return 0;
        }
        bool neg = false;
        if (ans < 0) {
            neg = true;
            ans = -ans;
        }
        string out;
        while (ans > 0) {
            out.push_back(char('0' + (int)(ans % 10)));
            ans /= 10;
        }
        if (neg) out.push_back('-');
        reverse(out.begin(), out.end());
        cout << out << "\n";
        return 0;
    }
    
    • 1

    信息

    ID
    8816
    时间
    2000ms
    内存
    512MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者