存储器区块错误(英语:Segmentation fault)发生这个错误一般就是空间溢出,注意数据类型和存储空间即可。
祼RMQ C++ 代码
void pushup(int rt)
{
Max[rt] = max(Max[rt<<1],Max[rt<<1|1]);
}
void build(int rt,int l,int r)
{
if(l==r)
{
Max[rt] = a[l];
return;
}
int m = (l+r)>>1;
build(rt<<1,l,m);//左子树
build(rt<<1|1,m+1,r);//右子树
pushup(rt);
}
void query(int L,int R,int l,int r,int rt)
{
if(L<=l &&R>=r)
{
mx = max(Max[rt],mx);
return;
}
int m = (l+r)>>1;
if(L<=m)
query(L,R,l,m,rt<<1);
if(R>m)
query(L,R,m+1,r,rt<<1|1);
}
int main()
{
int n,q;
cin>>n;
memset(a,0,sizeof(a));
memset(Max,-INF,sizeof(Max));
for(int i=1;i<=n;i++)
scanf("%ld",a+i);
build(1,1,n);
cin>>q;
for(int i=0;i<q;i++)
{
int l,r;
scanf("%d%d",&l,&r);
mx =-INF;
query(l,r,1,n,1);
cout<<mx<<endl;
}
return 0;
}
块 C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int nmax = 2e6+10;
const int INF = 0x3f3f3f3f;
const int mm = sqrt(2e6+10)+10;
int n,m;
int d[nmax],mmax[mm],block,num,L[mm],R[mm],belong[nmax];
void init(){
block = 2*sqrt(n);
num = n / block; if(n % block) num++;
for(int i = 1;i<=num;++i)
L[i] = (i-1) * block + 1,
R[i] = i * block,
d[i] = -INF;
R[num] = n;
}
int main() {
scanf("%d",&n);
init();
for(int i = 1;i<=n;++i){
scanf("%d",&d[i]);
belong[i] = (i-1) / block + 1;
mmax[belong[i]] = max(mmax[belong[i]],d[i]);
}
scanf("%d",&m);
int l,r;
for(int j = 1;j<=m;++j){
scanf("%d %d",&l,&r);
int ans = -INF;
for(int i = l;i<=min(r,R[belong[l]]);++i)
ans = max(ans,d[i]);
if(belong[r] != belong[l]) for(int i = L[belong[r]];i<=r;++i) ans = max(ans,d[i]);
for(int i = belong[l] + 1; i<= belong[r]-1;++i) ans = max(ans,mmax[i]);
printf("%d\n",ans);
}
return 0;
}
ST表 C++ 代码
void getRMQ() {
rep(i, 1, n) dp[i][0] = a[i];
for (int j = 1; (1 << j) <= n ; ++j) {
for (int i = 1; i + ( 1 << j ) - 1 <= n; ++i) {
dp[i][j] = max(dp[i][j - 1], dp[i + (1 << (j - 1 ))][j - 1]);
}
}
}
int RMQmax(int l, int r) {
int k = 0;
while ( (1 << (k + 1)) <= r - l + 1) ++k;
return max(dp[l][k], dp[r - (1 << k) + 1][k]);
}
int main() {
scanf("%d", &n);
rep(i, 1, n) scanf("%d", &a[i]);
getRMQ();
scanf("%d",&m);
int l, r;
rep(i, 1, m) {
scanf("%d%d", &l, &r);
printf("%d\n", RMQmax(l, r));
}
return 0;
}