Pagini recente » Cod sursa (job #1597688) | Cod sursa (job #316720) | Cod sursa (job #243436) | Cod sursa (job #2031071) | Cod sursa (job #881132)
Cod sursa(job #881132)
#include <stdio.h>
#include <stdlib.h>
const int CLUSTERSIZE = 100;
typedef struct {
short operatie;
int first, second;
} Operatie;
int N, M;
int *datorii;
Operatie *operatii;
int sumePartiale[151];
FILE *fout;
void citire()
{
FILE *fin = fopen("datorii.in", "r");
if (fin == NULL) perror("Error reading file!");
int index;
fscanf(fin, "%d %d", &N, &M);
datorii = (int *) malloc ((N + 1) * sizeof(int));
operatii = (Operatie *) malloc ((M + 1) * sizeof(Operatie));
for (index = 1; index <= N; index++)
fscanf(fin, "%d ", &datorii[index]);
for (index = 1; index <= M; index++)
{
int op, first, second;
fscanf(fin, "%d %d %d", &op, &first, &second);
operatii[index].operatie = op;
operatii[index].first = first;
operatii[index].second = second;
}
fclose(fin);
}
void creareSumePartiale()
{
int index;
for (index = 0; index <= 150; index ++)
sumePartiale[index] = 0;
for (index = 1; index <= N; index ++)
sumePartiale[index / CLUSTERSIZE] += datorii[index];
}
void actualizeaza(int index, int value)
{
datorii[index] -= value;
sumePartiale[index / CLUSTERSIZE] -= value;
}
int interogare(int start, int finish)
{
int index;
int startGroup = start / CLUSTERSIZE;
if (start % CLUSTERSIZE == 0) startGroup--;
int endGroup = finish / CLUSTERSIZE;
int result = 0;
for (index = startGroup + 1; index < endGroup; index ++)
result += sumePartiale[index];
while (start % CLUSTERSIZE != 0 && start <= finish)
{
result += datorii[start];
start ++;
}
while (finish % CLUSTERSIZE != 0 && finish >= start)
{
result += datorii[finish];
finish --;
}
if (start <= finish)
result += datorii[finish];
return result;
}
void procesare()
{
fout = fopen("datorii.out", "w");
int cursor;
for (cursor = 1; cursor <= M; cursor ++)
{
Operatie opCurent = operatii[cursor];
if (opCurent.operatie == 0)
actualizeaza(opCurent.first, opCurent.second); //zero-based index
else
{
int sum = interogare(opCurent.first, opCurent.second); //zero-based index
fprintf(fout, "%d\n", sum);
}
}
fclose(fout);
}
int main()
{
citire();
creareSumePartiale();
procesare();
return 0;
}