SPOJ GSS1 Can you answer these queries I(区间合并)

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值