SPOJ GSS1 Can you answer these queries I
2015-10-17 11:23
429 查看
Can you answer these queries I
Time Limit: 1000msMemory 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
$. $( |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
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 解题:线段树
#include <bits/stdc++.h> using namespace std; const int maxn = 50010; struct node{ int lt,rt,lsum,rsum,sum,msum; }tree[maxn<<2]; inline void pushup(int v){ tree[v].sum = tree[v<<1].sum + tree[v<<1|1].sum; tree[v].lsum = max(tree[v<<1].lsum,tree[v<<1].sum + tree[v<<1|1].lsum); tree[v].rsum = max(tree[v<<1|1].rsum,tree[v<<1|1].sum + tree[v<<1].rsum); tree[v].msum = max(max(tree[v<<1].msum,tree[v<<1|1].msum),tree[v<<1].rsum + tree[v<<1|1].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].msum = tree[v].lsum = tree[v].rsum = tree[v].sum; return; } int mid = (lt + rt)>>1; build(lt,mid,v<<1); build(mid + 1,rt,v<<1|1); pushup(v); } node query(int lt,int rt,int v){ if(lt <= tree[v].lt && rt >= tree[v].rt) return tree[v]; int mid = (tree[v].lt + tree[v].rt)>>1; if(rt <= mid) return query(lt,rt,v<<1); if(lt > mid) return query(lt,rt,v<<1|1); node a = query(lt,rt,v<<1); node b = query(lt,rt,v<<1|1); 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); return c; } int main(){ int n,m,x,y; while(~scanf("%d",&n)){ build(1,n,1); scanf("%d",&m); while(m--){ scanf("%d%d",&x,&y); node d = query(x,y,1); printf("%d\n",max(max(d.sum,d.msum),max(d.lsum,d.rsum))); } } return 0; }
View Code
相关文章推荐
- autolayout UIImageView 根据 UILabel的宽度变换位置
- MFC的CreateTimerQueueTimer和timeSetEvent两个高精度定时器的比较
- Queue类
- SPOJ GSS7 Can you answer these queries VII
- 利用运行时设置UITextField 光标颜色
- iOS界面编程-UIButton
- Difference between Key, Primary Key, Unique Key and Index in MySQL
- JAVA基础学习day23--GUI基础
- 精致的外观Request
- UITableViewCell的背景设置
- 自定义UILable 监听事件
- Displaying Bitmaps Efficiently (二)-----Processing Bitmaps Off the UI Thread
- SQL UNIQUE 约束 高级教程
- juicer语法
- *LeetCode-Unique Word Abbreviation
- iOS开发-UI控件:如何画1像素的线
- 【IOS 开发学习总结-OC-52】UITableViewDelegate详解
- 优化UITableViewCell高度计算
- getGuid()
- *LeetCode-Closest Binary Search Tree Value