码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ GSS1 Can you answer these queries I

时间:2015-10-17 12:01:59      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

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;
 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 }
12 void build(int lt,int rt,int v){
13     tree[v].lt = lt;
14     tree[v].rt = rt;
15     if(lt == rt){
16         scanf("%d",&tree[v].sum);
17         tree[v].lsum = tree[v].rsum = tree[v].sum;
18         return;
19     }
20     int mid = (lt + rt)>>1;
21     build(lt,mid,v<<1);
22     build(mid + 1,rt,v<<1|1);
23     pushup(v);
24 }
25 node query(int lt,int rt,int v){
26     if(lt <= tree[v].lt && rt >= tree[v].rt) return tree[v];
27     int mid = (tree[v].lt + tree[v].rt)>>1;
28     if(rt <= mid) return query(lt,rt,v<<1);
29     if(lt > mid) return query(lt,rt,v<<1|1);
30     node a = query(lt,rt,v<<1);
31     node b = query(lt,rt,v<<1|1);
32     node c;
33     c.sum = a.sum + b.sum;
34     c.lsum = max(a.lsum,a.sum + b.lsum);
35     c.rsum = max(b.rsum,b.sum + a.rsum);
36     return c;
37 }
38 int main(){
39     int n,m,x,y;
40     while(~scanf("%d",&n)){
41         build(1,n,1);
42         scanf("%d",&m);
43         while(m--){
44             scanf("%d%d",&x,&y);
45             node d = query(x,y,1);
46             printf("%d\n",max(d.sum,max(d.lsum,d.rsum)));
47         }
48     }
49     return 0;
50 }
View Code

 

SPOJ GSS1 Can you answer these queries I

标签:

原文地址:http://www.cnblogs.com/crackpotisback/p/4887164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!