RE 求助 玄关
查看原帖
RE 求助 玄关
1286983
HangingMirror楼主2025/2/7 13:55
#include<iostream>
#ifndef SparseTableDefined
#define SparseTableDefined
#include<vector>
std::vector<int> log(2,0);
class SparseTable {
private:
    std::vector<std::vector<int>> st;
public:
	SparseTable(){}
    SparseTable(const std::vector<int>& arr) {
        int n = arr.size();
        while(log.size()<n+1)log.push_back(log[log.size()/2]+1);
        
        st.assign(n, std::vector<int>(log[n] + 1));
        for (int i = 0; i < n; i++) {
            st[i][0] = arr[i];
        }
        
        for (int j = 1; j <= log[n]; j++) {
            for (int i = 0; i + (1 << j) <= n; i++) {
                st[i][j] = std::max(st[i][j - 1], st[i - (1 << (j - 1))][j - 1]);
            }
        }
    }
    
    void insertAtEnd(int value) {
        int n = st.size();
        while(log.size()<n+2)log.push_back(log[log.size()/2]+1);
        st.push_back(std::vector<int>(log[n+1] + 1, 0)); // Add a new row at the end
        st[n][0] = value; // Set the last element of this new row to the new value
        if(n == 0)return;
        for (int j = 1; j <= log[n+1]; j++) {
            st[n][j] = std::max(st[n][j-1], st[n - (1 << (j-1))][j-1]);
        }
    }
    
    int query(int l, int r) {
        int j = log[r - l + 1];
        return std::max(st[r][j], st[l + (1 << j) - 1][j]);
    }
};
#endif
using namespace std;

int main() {
    int n,q; 
    cin>>n>>q;
    SparseTable a,b;
    for(int i=0;i<n;++i){
    	int x;
    	cin>>x;
    	a.insertAtEnd(x);
    	b.insertAtEnd(-x);
	}
	for(int ii=0;ii<q;++ii){
		int l,r;
		cin>>l>>r;
		cout<<a.query(l,r)+b.query(l,r)<<endl;
	}
}

2025/2/7 13:55
加载中...