Cod sursa(job #1890687)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 23 februarie 2017 13:47:56
Problema Arbori de intervale Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.56 kb
#include <fstream>

using namespace std;

ifstream fin ("arbint.in");
ofstream fout ("arbint.out");

inline void update (unsigned int node, unsigned int left, unsigned int right);
inline void query (unsigned int node, unsigned int left, unsigned int right);

unsigned int N, M;
unsigned int A;
bool type;
unsigned int a, b;

int maxArb[100001];
unsigned int pos, val, start, finish;
int maximum;
unsigned int i;

int main ()
{
    fin >> N >> M;
    for (i=1; i<=N; i++)                    /// Create Tree
    {
        fin >> A;                           /// Read element A
        pos = i;                            /// Position of element A
        val = A;                            /// Value is the element A
        update(1,1,N);                      /// Add this value to the tree
    }
    for (i=1; i<=M; i++)
    {
        fin >> type >> a >> b;              /// Read queries
        if (type == 0)                      /// Calculate the max between [a,b]
        {
            maximum = -1;                   /// Initialize maximum with a value that not affects the calculus
            start = a;                      /// Start point is the left part of the interval
            finish = b;                     /// Finish is the right side
            query(1,1,N);                   /// Find the value
            fout << maximum << '\n';        /// Print it
        }
        else                                /// Value on position a is b
        {
            pos = a;                        /// Position is a
            val = b;                        /// Value is b
            update(1,1,N);                  /// Update the tree and change the value
        }
    }
    return 0;
}

inline void update (unsigned int node, unsigned int left, unsigned int right)       /// Create and update the tree
{
    unsigned int mid;
    if (left == right)
    {
        maxArb[node] = val;
        return;
    }
    mid = (left+right)/2;
    if (pos <= mid)
        update(2*node,left,mid);
    else
        update(2*node+1,mid+1,right);
    maxArb[node] = max(maxArb[2*node],maxArb[2*node+1]);
}

inline void query (unsigned int node, unsigned int left, unsigned int right)        /// Calculate the answer for the query
{
    unsigned int mid;
    if (start<=left && right<=finish)
    {
        if (maxArb[node] > maximum)
            maximum = maxArb[node];
        return;
    }
    mid = (left+right)/2;
    if (start <= mid)
        query(2*node,left,mid);
    if (mid < finish)
        query(2*node+1,mid+1,right);
}