Can you answer these queries I
Description
You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ). A query is defined as follows:
Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.
Given M queries, your program must output the results of these queries.
Input
- The first line of the input file contains the integer N.
- In the second line, N numbers follow.
- The third line contains the integer M.
- M lines follow, where line i contains 2 numbers xi and yi.
Output
- Your program should output the results of the M queries, one query per line.
Example
Input: 3 -1 2 3 1 1 2 Output: 2
Hint
Added by: | Nguyen Dinh Tu |
Date: | 2006-11-01 |
Time limit: | 0.115s-0.230s |
Source limit: | 5000B |
Memory limit: | 1536MB |
Cluster: | Cube (Intel G860) |
Languages: | All except: ERL JS NODEJS PERL 6 VB.net |
解题思路:
区间合并。
AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int N = 50005;
struct node{
int sum,mx,lx,rx;
inline node(int x = 0){
sum = mx = lx = rx = x;
}
}tree[N<<2];
int ql,qr;
node update(node x, node y){
node ans;
ans.sum = x.sum + y.sum;
ans.mx = max(x.rx + y.lx, max(x.mx, y.mx));
ans.lx = max(x.lx, x.sum + y.lx);
ans.rx = max(y.rx, y.sum + x.rx);
return ans;
}
void build(int id,int l,int r){
if(l == r){
int x;
scanf("%d",&x);
tree[id] = node(x);
return ;
}
int mid = (l+r)>> 1;
build(id<<1,l,mid);
build(id<<1|1,mid+1,r);
tree[id] = update(tree[id<<1], tree[id<<1|1]);
}
node query(int id,int l,int r){
if(ql <= l && r <= qr)
return tree[id];
node x(-INF), y(-INF);
x.sum = y.sum = 0;
int mid = (l+r)>> 1;
if (ql <= mid)
x = query(id<<1,l,mid);
if (qr > mid)
y = query(id<<1|1,mid+1,r);
return update(x,y);
}
int main(){
int n,m;
while(~scanf("%d", &n)){
build(1,1,n);
scanf("%d",&m);
while(m--){
scanf("%d%d",&ql,&qr);
printf("%d\n", query(1,1,n).mx);
}
}
return 0;
}