Cod sursa(job #1654026)

Utilizator Matei10Micu Matei Matei10 Data 16 martie 2016 19:26:49
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;


int N, M;
int *vec;
int *aux;
fstream f("aib2.in");
ofstream o("aib2.out");

int get_first_1(int x){
    return (x & ( ~ (x-1)));
}

void citire(){
    f >> N;
    f >> M;
    vec = new int[N+1];
    aux = new int[N+1];

    // citesc elementele
    for(int i = 1; i <= N; i++){
        f >> aux[i];
        vec[i] = 0;
    }

    // creez arborele 
    for(int i = 1; i <= N; i++){
        int a = get_first_1(i);
        for(int j = 0; j < a; j++){
            vec[i] += aux[i-j];
        }
    }

}

void update(int poz, int x){
    // adaug pe pozitia poz valoarea x
    while(poz <= N ){
        vec[poz] += x; 
        poz = poz + get_first_1(poz);
    }
}

void afisare_vec(){
    for(int i = 1; i <= N; i++)
        cout << vec[i] << " ";
    cout << endl;
}

int get_suma_1(int poz){
    int suma = 0;
    while(poz){
        int aux = get_first_1(poz);
        suma += vec[poz];
        poz = poz - aux;
    }

    return suma;
}

int get_suma_int(int p1, int p2){
    return get_suma_1(p2) - get_suma_1(p1-1);
}

int main(int argc, char *argv[])
{
    citire();
    // afisare_vec();

    for(int i = 0; i < M; i++){
        int comanda, a, b;
        f >> comanda;
        switch (comanda) {
            case 0:
                f >> a; 
                f >> b; 
                update(a, b);
                break;
            case 1:
                int aux;
                f >> a; 
                f >> b; 
                aux = get_suma_int(a, b);
                o << aux << endl;
                break;
            case 2:
                f >> a;
                int st = 1;
                int dr = N;
                int k = -1;
                // cout << "search : " << a << endl;
                while(st <= dr && a != 0){
                    int m = (st+dr) / 2;
                    // cout << "ST :" << st << endl;
                    // cout << "DR :" << dr << endl;
                    // cout << "Sum mij " << m << " :" << get_suma_1(m) << endl;

                 if(a == get_suma_1(m)){
                        // cout << "Am gasit " << m << endl;
                        k = m;
                        st = 1;
                        dr = -1;
                        }
 
                    if( get_suma_1(m) < a )
                        st = m+1;
 
                    if(get_suma_1(m) > a)
                        dr = m-1;
                    }
                o << k << "\n";
                break;

            }
    }
    
    f.close();
    o.close();
    return 0;
}