You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| <= 10000 , 1 <= N <= 10000 ). A query is defined as follows: Query(x1,y1,x2,y2) = Max { A[i]+A[i+1]+...+A[j] ; x1 <= i <= y1 , x2 <= j <= y2 and x1 <= x2 , y1 <= y2 }. Given M queries (1 <= M <= 10000), your program must output the results of these queries.
Input
The first line of the input consist of the number of tests cases <= 5. Each case consist of the integer N and the sequence A. Then the integer M. M lines follow, contains 4 numbers x1, y1, x2 y2.
Output
Your program should output the results of the M queries for each test case, one query per line.
Example
input: 2 6 3 -2 1 -4 5 2 2 1 1 2 3 1 3 2 5 1 1 1 1 1 1 1 output: 2 3 1
思路:
数很大,用树形结构。
套模板之后稍微改一下就好,改的地方主要是区间的最大值,则区间最大需要分情况,尤其是当从子到父的时候,直接看tree query()函数。
也可以由浅入深,一个一个慢慢改。
#include<iostream>
#include<string.h>
using namespace std;
typedef long long ll;
const int N=1e4;
int T,n,m;
int x1,x2,y1,y2;
ll a[N+5];
struct tree
{
ll sum,ans,lans,rans;
}t[N*4+5];
void pushup(int k)
{
t[k].sum =t[k*2].sum +t[k*2+1].sum ;
t[k].lans =max(t[k*2].lans ,t[k*2].sum +t[k*2+1].lans );
t[k].rans =max(t[k*2+1].rans ,t[k*2+1].sum +t[k*2].rans );
t[k].ans =max(max(t[k*2].ans ,t[k*2+1].ans ),t[k*2].rans +t[k*2+1].lans );
}
void build(int k,int l,int r)
{
if(l==r)
{
t[k].ans =t[k].lans =t[k].rans =t[k].sum =a[l];
return;
}
int mid=(l+r)/2;
build(k*2,l,mid);
build(k*2+1,mid+1,r);
pushup(k);
}
tree query(int k,int x,int y,int l,int r)
{
if(x>y)
return t[0];
if(x<=l&&y>=r)
return t[k];
int mid=(l+r)/2;
if(y<=mid)
return query(k*2,x,y,l,mid);
else if(x>mid)
return query(k*2+1,x,y,mid+1,r);
else
{
tree re,left,right;
left=query(k*2,x,y,l,mid);
right=query(k*2+1,x,y,mid+1,r);
re.sum =left.sum +right.sum ;
re.lans =max(left.lans ,left.sum +right.lans );
re.rans =max(right.rans ,right.sum +left.rans );
re.ans =max(max(right.ans ,left.ans ),left.rans +right.lans );
return re;
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
memset(t,0,sizeof(t));
memset(a,0,sizeof(a));
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
build(1,1,n);
scanf("%d",&m);
while(m--)
{
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
if(y1<x2)
{
printf("%lld\n",query(1,x1,y1,1,n).rans +query(1,y1+1,x2-1,1,n).sum +query(1,x2,y2,1,n).lans );
}
else
{
printf("%lld\n",max(query(1,x2,y1,1,n).ans ,
max(query(1,x1,x2,1,n).rans +query(1,x2,y2,1,n).lans -a[x2],query(1,x2,y1,1,n).rans +query(1,y1,y2,1,n).lans -a[y1])));
}
}
}
return 0;
}
该博客介绍了如何利用树状数组(也称作线段树)来高效地处理大规模序列的区间加法操作和区间查询最大值的问题。文章提供了一个实例,展示了如何构建树状数组并进行相关查询,包括区间最大值的特殊情况处理。代码示例中,给出了C++实现的详细过程,适用于处理包含大量数据的竞赛编程题目。
https://blog.csdn.net/TherAndI/article/details/122714595?spm=1001.2014.3001.5501

807

被折叠的 条评论
为什么被折叠?



