SPOJ Maximum Sum

//I am struggling
//Just Not Good at it

// Accepted

//I am struggling
//Just Not Good at it


#include<bits/stdc++.h>

using namespace std;

#define fast ios_base::sync_with_stdio(false)
#define bfast cin.tie(0)
#define outs(x) cout << x << " "
#define outn(x) cout << x << "\n"
#define sf scanf
#define pf printf
#define nl puts("")
#define psb push_back

typedef long long LL;
typedef vector<int>vii;
typedef vector<LL>vll;

const int mod = 1000007;
const int high = 100010;
const int inf = 1 << 30;

int ar[high];

struct info
{
    LL pos, maxi;
}tree[high * 4] , base;

void update(int node, int b , int e , int i ,  LL x)
{
    if(i>e or i<b) return;

    if(b == e)
    {
        tree[node].maxi = x;
        tree[node].pos = i;
        return;
    }

    int Left = node << 1;
    int Right = Left + 1;
    int mid = (b + e) >> 1;

    update(Left , b , mid , i , x);
    update(Right, mid+1, e , i , x);

    if(tree[Left].maxi > tree[Right].maxi)
    {
        tree[node].maxi = tree[Left].maxi;
        tree[node].pos = tree[Left].pos;
    }

    else
    {
        tree[node].maxi = tree[Right].maxi;
        tree[node].pos = tree[Right].pos;
    }
}

info query(int node, int b , int e, int i, int j)
{
    if(i>e or j<b) return base;

    if(b>=i and e<=j)
    {
        return tree[node];
    }

    int Left = node << 1;
    int Right = Left + 1;
    int mid = (b + e) >> 1;

    info p1 = query(Left, b , mid, i , j);
    info p2 = query(Right, mid+1, e , i , j);

    if(p1.maxi > p2.maxi) return p1;
    else return p2;
}

int main()
{
    int n , q , i , j;
    LL x , mx1 , mx2 , posn;
    //mplli mp;
    char ch;
    while(sf("%d", &n)==1)
    {

        //mp.clear();

        for(i=1; i<=n; i++)
        {
            sf("%d", &ar[i]);
            //mp[ar[i]] = i; //cout << mp[ar[i]] << "; ";
            update(1 , 1 , n , i, ar[i]);
        }

        //build(1 , 0 , n-1);

        sf("%d", &q);

        while(q--)
        {
            getchar();

            //string s;
            //cin >> s;
            sf("%c", &ch);

            if(ch == 'Q')
            {
                sf("%d %d", &i , &j);

                info ret = query(1 , 1 , n , i , j);

                mx1 = ret.maxi;
                posn = ret.pos;

                update(1, 1 , n , posn , 0);

                ret = query(1, 1, n , i , j);

                mx2 = ret.maxi;

                pf("%lld\n", mx1 + mx2);

                update(1 , 1 , n , posn , mx1);
            }

            else
            {
                sf("%d %lld", &i , &x);

                //ar[i] = x;

                update(1 , 1 , n , i , x);
            }
        }
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number