Cod sursa(job #1012776)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 19 octombrie 2013 17:07:43
Problema SequenceQuery Scor 90
Compilator cpp Status done
Runda maricei1 Marime 2.56 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <utility>
#include <cstring>
#include <string>
#include <stack>
#include <deque>
#include <iomanip>
#include <set>
#include <map>
#include <cassert>
#include <ctime>
#include <list>
#include <iomanip>

using namespace std;

string file = "sequencequery";

ifstream cin( (file + ".in").c_str() );
ofstream cout( (file + ".out").c_str() );

const int MAXN = 100005;
const int oo = 1<<25;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

struct Node {
    int Sum;
    int Pref;
    int Suf;
    int Best;
    Node() {
        Update(-oo);
    }
    void Update(const int &Value) {
        Sum = Value;
        Pref = Value;
        Suf = Value;
        Best = Value;
    }
    void Update(const Node &Left, const Node &Right) {
        Sum = Left.Sum + Right.Sum;
        Pref = max(Left.Pref, Left.Sum + Right.Pref);
        Suf = max(Right.Suf, Right.Sum + Left.Suf);
        Best = max(Left.Best, Right.Best);
        Best = max(Best, Left.Suf + Right.Pref);
    }
};

Node Aint[1 << 19];

inline void Update(int actNode, int st, int dr, int pos, int value) {
    if(st == dr) {
        Aint[actNode].Update(value);
        return;
    }
    int mid = ((st + dr) >> 1);
    if(pos <= mid)
        Update(2*actNode, st, mid, pos, value);
    else Update(2*actNode + 1, mid + 1, dr, pos, value);
    Aint[actNode].Update(Aint[2*actNode], Aint[2*actNode + 1]);
}

Node Query(int actNode, int st, int dr, int a, int b) {
    if(a <= st && dr <= b)
        return Aint[actNode];
    int mid = ((st + dr) >> 1);
    Node left, right;
    if(a <= mid)
        left = Query(2 * actNode, st, mid, a, b);
    if(mid < b)
        right = Query(2 * actNode + 1, mid+1, dr, a, b);
    Node Father;
    Father.Update(left, right);
    return Father;
}

int N, M;

int main() {
    cin >> N >> M;
    for(int i = 1 ; i <= N ; ++ i) {
        int x;
        cin >> x;
        Update(1, 1, N, i, x);
    }
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        cin >> x >> y;
        cout << Query(1, 1, N, x, y).Best << '\n';
    }
    cin.close();
    cout.close();
    return 0;
}