Pagini recente » Cod sursa (job #2368300) | Cod sursa (job #566916) | Cod sursa (job #1120416) | Cod sursa (job #2807733) | Cod sursa (job #1341998)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author bugyvlad
*
*/
public class Main {
public static int N, M;
public static int[] aib;
/*
* Citire
*/
public static BufferedReader citireFisier() throws IOException {
BufferedReader fin = new BufferedReader(new FileReader("aib.in"));
String line = fin.readLine();
String[] numbers = line.split(" ");
N = Integer.parseInt(numbers[0]);
M = Integer.parseInt(numbers[1]);
line = fin.readLine();
numbers = line.split(" ");
aib = new int[numbers.length+1]; //AIB
for (int i = 1; i <= N; i++) {
int val = Integer.parseInt(numbers[i-1]);
//Construim vectorul pentru arborele indexat binar
adaugaLaPoz(i, val);
}
return fin;
}
/*
* Adauga b la pozitia a.
*/
public static void adaugaLaPoz(int a, int b) {
aib[a] += b;
int index = a;
while (true) {
index += (index&(-index));
if (index <= N) {
aib[index] += b;
} else {
break;
}
}
}
/*
* Suma elementelor din intervalul [1,poz]
*/
public static int suma(int poz) {
int suma = 0;
while (poz > 0) {
suma += aib[poz];
poz -= (poz&(-poz));
}
return suma;
}
/*
* Cautare binara pentru suma value.
*/
public static int cautareBinara(int value) {
int left = 1;
int right = N;
while (left <= right) {
int mij = (left+right)/2;
int valMij = suma(mij);
if (valMij == value) {
//Salvam pozitia k si verificam daca exista o pozitie k mai mica.
int k = mij;
for (int index = mij-1; index >= 1; index--) {
if (suma(index) == value) {
k = index;
}
}
return k;
} else if (valMij > value) {
right = mij - 1;
} else {
left = mij +1;
}
}
return -1;
}
public static void main(String[] args) throws IOException {
BufferedReader fin = citireFisier();
BufferedWriter fout = new BufferedWriter(new FileWriter("aib.out"));
String line;
String[] numbers;
for (int t = 0; t < M; t++) {
line = fin.readLine();
numbers = line.split(" ");
if (numbers[0].compareTo("0") == 0) {
adaugaLaPoz(Integer.parseInt(numbers[1]), Integer.parseInt(numbers[2]));
} else if (numbers[0].compareTo("1") == 0) {
fout.write(Integer.toString(suma(Integer.parseInt(numbers[2])) - suma(Integer.parseInt(numbers[1])-1)));
fout.write("\n");
} else {
int value = Integer.parseInt(numbers[1]);
fout.write(Integer.toString(cautareBinara(value)));
fout.write("\n");
}
}
fin.close();
fout.close();
}
}