Cod sursa(job #1417598)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 10 aprilie 2015 17:20:27
Problema Datorii Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.4 kb
#include <stdio.h>

#define MAX_N 15000
#define MAX_SQRT 123

int a[MAX_N];
int s[MAX_SQRT];
int rad;

inline void update(int day, int sum) {
  a[day] -= sum;
  s[day / rad] -= sum;
}
inline int query(int lo, int hi) {
  int bucketLO = (lo / rad); // bucket-ul in care se gaseste lo
  int bucketHI = (hi / rad); // bucket-ul in care se gaseste hi
  int ans = 0;

  if (bucketLO == bucketHI) { // sunt in acelasi bucket
    for (int i = lo; i <= hi; i++) {
      ans += a[i];
    }
  } else {
    for (int i = bucketLO + 1; i < bucketHI; i++) { // adun bucket-urile dintre cele 2 pozitii
      ans += s[i];
    }
    for (int i = bucketHI * rad; i <= hi; i++) { // resturi dreapta
      ans += a[i];
    }
    int endLO = bucketLO * rad + rad;
    for (int i = lo; i < endLO; i++) { // resturi stanga
      ans += a[i];
    }
  }
  return ans;
}
int main(void) {
  FILE *f, *g;
  int n, m;
  int x, y, type;

  f = fopen("datorii.in", "r");
  fscanf(f, "%d%d", &n, &m);
  rad = 1;
  while ((rad + 1) * (rad + 1) <= n) {
    rad++;
  }

  for (int i = 0; i < n; i++) {
    fscanf(f, "%d", &a[i]);
    s[i / rad] += a[i];
  }
  g = fopen("datorii.out", "w");
  for (; m; m--) {
    fscanf(f, "%d%d%d", &type, &x, &y);
    if (!type) {
      update(x - 1, y);
    } else {
      fprintf(g, "%d\n", query(x - 1, y - 1));
    }
  }
  fclose(f);
  fclose(g);
  return 0;
}