SPOJ GSS1 Can you answer these queries I

Can you answer these queries I

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

You are given a sequence $A[1], A[2], ..., A[N] $. $( |A[i]| \leq 15007 , 1\leq N \leq 50000 )$. A query is defined as follows: 
$Query(x,y) = Max \{ a[i]+a[i+1]+...+a[j] ; x \leq i \leq j \leq y \}$. 
Given M queries, your program must output the results of these queries.

Input

  1. The first line of the input file contains the integer N.

  2. In the second line, N numbers follow.

  3. The third line contains the integer M.

  4. 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

解题:线段树
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 50010;
 4 struct node{
 5     int lt,rt,lsum,rsum,sum,msum;
 6 }tree[maxn<<2];
 7 inline void pushup(int v){
 8     tree[v].sum = tree[v<<1].sum + tree[v<<1|1].sum;
 9     tree[v].lsum = max(tree[v<<1].lsum,tree[v<<1].sum + tree[v<<1|1].lsum);
10     tree[v].rsum = max(tree[v<<1|1].rsum,tree[v<<1|1].sum + tree[v<<1].rsum);
11     tree[v].msum = max(max(tree[v<<1].msum,tree[v<<1|1].msum),tree[v<<1].rsum + tree[v<<1|1].lsum);
12 }
13 void build(int lt,int rt,int v){
14     tree[v].lt = lt;
15     tree[v].rt = rt;
16     if(lt == rt){
17         scanf("%d",&tree[v].sum);
18         tree[v].msum = tree[v].lsum = tree[v].rsum = tree[v].sum;
19         return;
20     }
21     int mid = (lt + rt)>>1;
22     build(lt,mid,v<<1);
23     build(mid + 1,rt,v<<1|1);
24     pushup(v);
25 }
26 node query(int lt,int rt,int v){
27     if(lt <= tree[v].lt && rt >= tree[v].rt) return tree[v];
28     int mid = (tree[v].lt + tree[v].rt)>>1;
29     if(rt <= mid) return query(lt,rt,v<<1);
30     if(lt > mid) return query(lt,rt,v<<1|1);
31     node a = query(lt,rt,v<<1);
32     node b = query(lt,rt,v<<1|1);
33     node c;
34     c.sum = a.sum + b.sum;
35     c.lsum = max(a.lsum,a.sum + b.lsum);
36     c.rsum = max(b.rsum,b.sum + a.rsum);
37     c.msum = max(max(a.msum,b.msum),a.rsum + b.lsum);
38     return c;
39 }
40 int main(){
41     int n,m,x,y;
42     while(~scanf("%d",&n)){
43         build(1,n,1);
44         scanf("%d",&m);
45         while(m--){
46             scanf("%d%d",&x,&y);
47             node d = query(x,y,1);
48             printf("%d\n",max(max(d.sum,d.msum),max(d.lsum,d.rsum)));
49         }
50     }
51     return 0;
52 }
View Code

 

posted @ 2015-10-17 11:23  狂徒归来  阅读(330)  评论(0编辑  收藏  举报