您的位置:首页 > 产品设计 > UI/UE

SPOJ GSS5 Can you answer these queries V

2015-10-18 17:19 435 查看

Can you answer these queries V

Time Limit: 1000ms
Memory Limit: 262144KB
This problem will be judged on SPOJ. Original ID: GSS5
64-bit integer IO format: %lld Java class name: Main

You are given a sequence A[1], A[2], ..., A
. ( |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

解题:线段树,两个区间交与不交 讨论即可


#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct node{
int lt,rt,lsum,rsum,sum,msum;
}tree[maxn<<2];
int A[maxn];
inline void pushup(node &a,node &b,node &c){
c.sum = a.sum + b.sum;
c.lsum = max(a.lsum,a.sum + b.lsum);
c.rsum = max(b.rsum,b.sum + a.rsum);
c.msum = max(max(a.msum,b.msum),a.rsum + b.lsum);
}
void build(int lt,int rt,int v){
tree[v].lt = lt;
tree[v].rt = rt;
if(lt == rt){
scanf("%d",&tree[v].sum);
tree[v].lsum = tree[v].rsum = tree[v].msum = tree[v].sum;
A[lt] = tree[v].sum;
return;
}
int mid = (lt + rt)>>1;
build(lt,mid,v<<1);
build(mid + 1,rt,v<<1|1);
pushup(tree[v<<1],tree[v<<1|1],tree[v]);
}
node query(int lt,int rt,int v){
if(lt > rt){
node tmp;
tmp.sum = tmp.lsum = tmp.rsum = tmp.msum = 0;
return tmp;
}
if(lt <= tree[v].lt && rt >= tree[v].rt) return tree[v];
if(rt <= tree[v<<1].rt) return query(lt,rt,v<<1);
if(lt >= tree[v<<1|1].lt) return query(lt,rt,v<<1|1);
node a = query(lt,rt,v<<1),b = query(lt,rt,v<<1|1),c;
pushup(a,b,c);
return c;
}
int main(){
int kase,n,m,x1,y1,x2,y2;
scanf("%d",&kase);
while(kase--){
scanf("%d",&n);
build(1,n,1);
scanf("%d",&m);
while(m--){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
if(y1 < x2){
int a = query(x1,y1,1).rsum;
int b = query(x2,y2,1).lsum;
int c = x2 - y1 > 1?query(y1+1,x2-1,1).sum:0;
printf("%d\n",a + b + c);
}else{
int a = query(x1,x2,1).rsum + query(x2,y1,1).lsum - A[x2];
int b = query(x1,y1,1).rsum + query(y1,y2,1).lsum - A[y1];
int c = query(x2,y1,1).msum;
printf("%d\n",max(max(a,b),c));
}
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: