Cod sursa(job #2905610)

Utilizator KarinaDKarina Dumitrescu KarinaD Data 22 mai 2022 16:51:28
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100001;
int v[N], aib[N];


int main () {
    
    int n, m, i, x, c, a, b;
    
    fin >> n >> m;
    
    for ( i = 1; i <= n; i++ ) {
        
        fin >> v[i];
        
        x = i;
        
        while ( x <= n ){
            aib[x] = aib[x] + v[i];
            x = x + ( x & (-x) );
        }
    }
    
    for ( i = 0; i < m; i++ ){
        
        fin >> c;
        
        if ( c == 0 ){
            
            fin >> a >> b;
            
            while ( a <= n ) {
                aib[a] = aib[a] + b;
                a = a + ( a & (-a) );
            }
            
        }
        
        else if ( c == 1 ){
            
            fin >> a >> b;
            
            int sa = 0, sb = 0;
            
            a--;
            while ( a > 0 ){
                sa = sa + aib[a];
                a = a - ( a & (-a) );
            }
            
            while ( b > 0 ){
                sb = sb + aib[b];
                b = b - ( b & (-b) );
            }
            
            fout << sb - sa << "\n";
            
        }
        
        else if ( c == 2 ) {
            
            fin >> a;
            
            int st = 0, dr = n + 1, mij, s;
            
            while ( dr - st > 1 ){
                
                mij = x = ( st + dr ) / 2;
                s = 0;
                
                while ( x > 0 ){
                    s = s + aib[x];
                    x = x - ( x & (-x) );
                }
                
                if ( s < a )
                    st = mij;
                else
                    dr = mij;

            }
            
            x = st + 1;
            s = 0;
            
            while ( x > 0 ){
                s = s + aib[x];
                x = x - ( x & (-x) );
            }
            
            if ( s == a )
                fout << st + 1 << "\n";
            else
                fout << "-1\n";
            
        }
        
    }
    
    
    
    return 0;
}