树状数组求调
查看原帖
树状数组求调
572891
Run24楼主2024/11/20 19:56
#include <bits/stdc++.h>
#define lowbit(x) (x&(-x)) 
#define ll long long int
using namespace std;
inline ll read(){
    ll x=0,f=1;
    char z=getchar();
    while(z<'0'||z>'9'){
        if(z=='-') f=-1;
        z=getchar();
    }
    while(z>='0'&&z<='9') x=x*10+(z^48),z=getchar();
    return x*f;
}
const int maxn = 80001;
int n, q, h[maxn];
struct node{
	int mx, mn;
}tree[maxn];
void init() {
	for(int i=0; i<=maxn; i++)
		tree[i].mx=-1, tree[i].mn=0x3f3f3f3f;
}
void add(int pos, int x) {
	for(int i=pos; i<=n; i+=lowbit(i)) {
		tree[i].mx = max(x, tree[i].mx);	
		tree[i].mn = min(x, tree[i].mn);	
	}
}
int query(int l, int r) {
	int maxx=-1, minn=0x3f3f3f3f;
	while(l <= r) {
		for(int i=r; i>=l; i-=lowbit(i)) {
			maxx=max(tree[r].mx, maxx);
            minn=min(tree[r].mn, minn);
		}
		maxx = max(maxx, h[r]);
		minn = min(minn, h[r]);
		r--;
	}
	return maxx-minn;
}
int a, b;
signed main() {
	n=read(), q=read();
	init();
	for(int i=1; i<=n; i++) {
		h[i] = read();
		add(i, h[i]);
	}
	while(q--) {
		a=read(), b=read();
		printf("%d\n", query(a, b));
	}
    return 0;
}

错误我不到啊

2024/11/20 19:56
加载中...