UVA11235 频繁出现的数值 ——RMQ

蓝书p198

题意:

给出一个非降序排列的整数数组,回答一系列询问,找出[l, r]中出现次数最多的值所出现的次数。

注意第52、55行对边界的处理

由于数组从下标为0开始存储的,所以最后回答询问的时候l--,r--

// Decline is inevitable,
// Romance will last forever.
//#include <bits/stdc++.h>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <deque>
#include <vector>
using namespace std;
#define mst(a, x) memset(a, x, sizeof(a))
#define INF 0x3f3f3f3f
//#define mp make_pair
#define pii pair<int,int>
#define fi first
#define se second
#define ll long long
//#define int long long
const int maxn = 1e5 + 10;
const int maxm = 25;
const int P = 1e9 + 7;
int n, q;
struct RMQ {
    int d[maxn][30];
    void init(const vector<int>& A) {
        int n = (int)A.size();
        for(int i = 0; i < n; i++) d[i][0] = A[i];
        for(int j = 1; (1 << j) <= n; j++)
            for(int i = 0; i+(1<<j)-1<n; i++)
                d[i][j] = max(d[i][j-1], d[i+(1<<(j-1))][j-1]);
    }
    int query(int l, int r) {
        int len = r - l + 1;
        int k = 0;
        while((1<<(k+1))<=len) k++;
        return max(d[l][k], d[r-(1<<k)+1][k]);
    }
}rmq;
int a[maxn], num[maxn], le[maxn], ri[maxn];
signed main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    while(cin >> n && n) {
        cin >> q;
        for(int i = 0; i < n; i++)
            cin >> a[i];
        a[n] = a[n-1] + 1;  //
        vector<int> count;
        int start = -1;
        for(int i = 0; i <= n; i++) {       //
            if(i == 0 || a[i] != a[i-1]) {
                if(i > 0) {
                    count.push_back(i-start);
                    for(int j = start; j < i; j++) {
                        num[j] = (int)count.size() - 1;
                        le[j] = start;
                        ri[j] = i-1;
                    }
                }
                start = i;
            }
        }
        rmq.init(count);
        while(q--) {
            int l, r;
            cin >> l >> r;
            l-- ; r--;  //
            int ans = 0;
            if(num[l] == num[r]) ans = r - l + 1;
            else {
                ans = max(ri[l]-l, r-le[r]) + 1;
                if(num[l]+1<num[r])
                    ans = max(ans, rmq.query(num[l]+1, num[r]-1));
            }
            cout << ans << '\n';
        }
    }
    return 0;
}

上一篇:压位单调栈实现线性 rmq


下一篇:大量比特币矿工布局Filecoin和Chia Cloudrush助力构建完善的分布式存储网络